How to pass the full Model from view to controller

2019-04-16 17:23发布

问题:

I have a list of checkbox's and textbox's. I want to let the user add items to the list via a partial view modal popup.

After the user adds an item to the list, if any items on the original view have values in them, I want them preserved, and the page refreshed with the added items.

I want to send the full model back to the controller from the original view, I can then just add the new items to that model and pass the model back to the original page and have all my values preserved.

I could grab all the values and pass them via loops and such in javascript (very tedious), but I think the full model would be the easiest way.

I sawe a link from Laviak on a post from here..., but I can't get it to work.

it states.... If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.

In our app, we do this with an extension method:

public static class JsonExtensions 
{ 
    public static string ToJson(this Object obj) 
    { 
       return new JavaScriptSerializer().Serialize(obj); 
   } 
} 

On the view, we use it to render the model:

<script type="javascript"> 
  var model = <%= Model.ToJson() %> 
</script> 

You can then pass the model variable into your $.ajax call.

Has anyone got this to work???

Thanks Bill

回答1:

you can do something like this:

<script type="text/javascript">
    var dataViewModel = @Html.Raw(Json.Encode(Model)); //Make sure you send the proper model to your view

    function MethodPost(param1, param2, etc...) {

    dataviewModel.Param1 = param1; //Or load a value from jQuery
    dataviewModel.Param2 = $("#param2").val();

    }

    //Pass it to a controller method
    $.post("@Url.Action(MVC.Home.PostMethodInController())", { viewModel: JSON.stringify(dataViewModel)} , function(data) {
        //Do something with the data returned.
    }
</script>

In the controller you get your class/model using Json.Net which is available on nuget.

    public virtual ActionResult Index()
    {
        return View(new MyModelToView());//Send at least an empty model
    }

    [HttpPost]
    public virtual JsonResult PostMethodInController(string viewModel)
    {
        var entity = JsonConvert.DeserializeObject<MyObject>(viewModel);

        //Do Something with your entity/class

        return Json(entity, JsonRequestBehavior.AllowGet);
    }

Hope this helps.