How to send a model in jQuery $.ajax() post request to MVC controller method

前端 未结 7 1851
南方客
南方客 2020-11-27 02:47

In doing an auto-refresh using the following code, I assumed that when I do a post, the model will automatically sent to the controller:

$.ajax({
    url: \'         


        
7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 03:01

    The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.

    As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.

    For example, the Javascript:

    var values = 
    {
        "Name": "Chris",
        "Color": "Green"
    }
    
    $.post("@Url.Action("Update")",values,function(data)
    {
        // do stuff;
    });
    

    The model:

    public class UserModel
    {
         public string Name { get;set; }
         public string Color { get;set; }
         public IEnumerable Contacts { get;set; }
    }
    

    The controller:

    public ActionResult Update(UserModel model)
    {
         // do something with the model
    
         return Json(new { success = true });
    }
    

提交回复
热议问题