简体   繁体   中英

Passing Strongly Typed View Model to Controller as Paramter via Ajax

I have looked at like twenty answers on here regrading this and none of them seem to be working for me. They all seem hackish as well.

I have this huge View model that I am trying to pass back and forth between two PartialViewResults via Ajax. However, nothing seems to work.

Here is a "generic" version of my code:

Controller

public PartialViewResult _View1(Model model)
{
  return PatialView(model);
}

*I have another one of these for Partial view2*

View

<div id="div1">Load View 1 here</div>

<script>
var m = @Html.Raw(Json.Encode(Model));
    console.log(m);
    $.ajax({
        url: '@Url.Action("_View1")',
        data: {'model' : m},
        dataType: "html",
        success: function (result) {
            $("#View1").html(result);
        },
        error: function (e) {
            $("#View1").html("<div class='alert alert-danger' role='alert'>Error: Getting View.</div>");
        }
    });
</script>

I have tried various configurations on my ajax calls. Any help would be awesome thank you. I do not want to have to store each variable of the view model into vars and pass them individually to the controller. The view model is way too big for this.

*Note: When i do a console.log(m) the console of my browser shows me all of my view data. I am just unsure how to pass all of that data to the controller

Note2: If there is a solution that is on stackoverflow already, please feel free to link to it. For some reason i wasn't able to find it.*

As data type of the parameter is an object you should pass it to your controller as JSON format. Your ajax options should be like this

$.ajax({
    url: '@Url.Action("_View1")',
    contentType: "application/json", //tell ajax the data you send is JSON format
    data: JSON.stringify(m),
    success: function (result) {
        $("#View1").html(result);
    },
    error: function (e) {
        $("#View1").html("<div class='alert alert-danger' role='alert'>Error: Getting View.</div>");
    }
});

Hope it helps

var m = $('#Form').serialize();   
 $.post( "@Url.Action("_View1")", m)
            .done(function( data ) {
                console.log('done default');
                $("#View1").html(data);
            })
            .always(function() {
                console.log('Done')
                    });

The problem I was running into was that my view model had two binding for a method via a hidden input. This was causing serialization issues. But serializing the form and passing it as the Model Object back to the controller worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM