如何在jQuery的$。阿贾克斯()POST请求到MVC控制器的方法来发送模式 [英] How to send a model in jQuery $.ajax() post request to MVC controller method

查看:120
本文介绍了如何在jQuery的$。阿贾克斯()POST请求到MVC控制器的方法来发送模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用以下code做一个自动刷新,我认为当我做了后,该模型将自动发送到控制器:

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: '<%=Url.Action("ModelPage")%>',
    type: "POST",
    //data:  ??????
    success: function(result) {
        $("div#updatePane").html(result);
    },

    complete: function() {
    $('form').onsubmit({ preventDefault: function() { } });

    }
});

每当有一个帖子,我需要增加模型的数值属性:

Every time there is a post, I need to increment the value attribute in the model:

public ActionResult Modelpage(MyModel model)
    {                   
        model.value = model.value + 1;

        return PartialView("ModelPartialView", this.ViewData);
    }

但是,当页面发布使用jQuery AJAX请求模式不传递给控制器​​。我如何发送模型中的AJAX请求?

But the model is not passed to the controller when the page is posted with jQuery AJAX request. How can I send the model in the AJAX request?

推荐答案

简单的答案(在MVC 3起,甚至2)是你没有做什么特别的事情。

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

只要你的JSON参数匹配模型,MVC是足够聪明,从你给它的参数构造一个新的对象。那不是参数有只是拖欠。

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.

例如,JavaScript的:

For example, the Javascript:

var values = 
{
    "Name": "Chris",
    "Color": "Green"
}

$.post("@Url.Action("Update")",values,function(data)
{
    // do stuff;
});

模型:

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

控制器:

public ActionResult Update(UserModel model)
{
     // do something with the model

     return Json(new { success = true });
}

这篇关于如何在jQuery的$。阿贾克斯()POST请求到MVC控制器的方法来发送模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆