Search code examples
javascriptc#ajaxasp.net-mvcviewmodel

Convert JSON to ViewModel and pass with token to Controller


In my ASP:NET MVC app I have a method as shown below and I try to pass the form data (single item of a list) to the Controller. I also need to pass __RequestVerificationToken as I use POST method in the Controller. I have look at many topics on stackoverflow but none of them has fixed this problem.

Razor:

@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>

On the other hand, normally I would use var formdata = $('#frmEmployee').serialize(); or var formdata = new FormData($('#frmEmployee').get(0)); but in this example I need to get a single data from list rather than form data.

Controller:

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

When passing the data to Controller model variable is null or when trying something the values of the model are null. Any idea to fix the problem?


Solution

  • Finally I fixed the problem using the following approach. So, anyone who need to convert JSON to ViewModel in ASP.NET MVC can use the following approach:

    View:

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

    Controller:

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