将 JSON 转换为 ViewModel 并将令牌传递给 Controller

Convert JSON to ViewModel and pass with token to Controller

在我的 ASP:NET MVC 应用程序中,我有一个如下所示的方法,我尝试将表单数据(列表的单个项目)传递给控制器​​。我还需要传递 __RequestVerificationToken,因为我在控制器中使用 POST 方法。我看过很多关于 Whosebug 的话题,但是 none 已经解决了这个问题。

剃须刀:

@model IEnumerable<DemoViewModel>

@using (Html.BeginForm("Save", "Employee", FormMethod.Post, 
    new { id = "frmEmployee", enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    @foreach (var item in Model)
    {
        @item.Name
        @item.Surname
        @item.Town
        <!-- code omitted for brevity -->                                                
    }
}

<a href="javascript:save();">
    Save
</a>


<script>

    function save() {

        var selectedEmpId = 0;
        var employeeList = @Html.Raw(Json.Encode(Model));        
        var employee = employeeList.filter(function (e) { return e.Id === selectedEmpId; });

        var formdata = JSON.stringify({employee});
        var token = $('[name=__RequestVerificationToken]').val();

        $.ajax({
            type: "POST",
            url: '@Url.Action("Save", "Employee")',
            cache: false,
            dataType: "json",
            data: { model: formdata, __RequestVerificationToken: token },

            //I also tried  to add this
            //contentType: "application/json; charset=utf-8", 
        });
    };

</script>

另一方面,通常我会使用 var formdata = $('#frmEmployee').serialize();var formdata = new FormData($('#frmEmployee').get(0)); 但在这个例子中我需要从列表而不是表单数据中获取单个数据。

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save([Bind(Exclude = null)] DemoViewModel model)
{
    if (ModelState.IsValid)
    {
        //stuff
    }
}

当将数据传递给 Controller 时,模型变量为 null 或尝试执行某些操作时,模型的值为 null。有解决问题的想法吗?

通过过滤数组,您得到的结果是包含一个员工项目的数组,并且在控制器操作中需要一个对象而不是 array/list。所以传递过滤列表的第一个元素或更好地使用 find 方法,

var employee = employeeList.find(e => e.Id === selectedEmpId);
var formdata = JSON.stringify(employee);

和post它

$.ajax({
        type: "POST",
        url: '@Url.Action("Save", "Employee")',
        cache: false,
        dataType: "json",
        data: formdata,
        contentType: 'application/json; charset=utf-8', 

        //....success,error functions
    });

应该在操作方法中正确绑定模型。如果仍然面临绑定问题,您可以使用 FromBody 属性和参数。

最后我使用以下方法解决了这个问题。因此,任何需要在 ASP.NET MVC 中 将 JSON 转换为 ViewModel 的人都可以使用以下方法:

视图:

$.ajax({
    type: "POST",
    url: '@Url.Action("Save", "DemoContoller")',
    cache: false,
    dataType: "json",
    data: { json: JSON.stringify(demoData), "__RequestVerificationToken": 
        $('input[name=__RequestVerificationToken]').val() },

    //...
});

控制器:

public ActionResult Save(string json)
{ 
    IList<DemoViewModel> model = new
        JavaScriptSerializer().Deserialize<IList<DemoViewModel>>(json);

    //or

    List<DemoViewModel> model = new 
        JavaScriptSerializer().Deserialize<List<DemoViewModel>>(json);
}