如何将jquery.post中的数据发送到使用ViewModel作为参数的mvc控制器?

Rad*_*lav 24 asp.net-mvc jquery visual-studio-2010 c#-4.0

我正在用asp.net mvc编写应用程序.我有控制器动作,它使用一些ViewModel作为参数.如何使用jquery post将表单数据发送到该mvc控制器.

Shy*_*yju 39

$.post("Yourcontroller/YourAction", { FirstName : $("#txtFirstName").val(), LastName : $("#txtLastName") } ,function(data){
  //do whatever with the response

});
Run Code Online (Sandbox Code Playgroud)

您传递的ViewModel属性名称和参数应该相同.即:您的视图模型应该有2个属性,FirstName并且LastName像他一样

public class PersonViewModel
{
  public string FirstName { set;get;}
  public string LastName { set;get;}
  // other properties

}
Run Code Online (Sandbox Code Playgroud)

并且您的Post动作方法应该接受类型的参数 PersonViewModel

[HttpPost]
public ActionResult YourAction(PersonViewModel model)
{
  //Now check model.FirstName 
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您的视图是强类型的PersonViewModel,您只需使用jQuery serialize方法将序列化的表单发送到action 方法

$.post("Yourcontroller/YourAction", $("#formId").serialize() ,function(data){
  //do whatever with the response

});
Run Code Online (Sandbox Code Playgroud)

编辑:根据评论

Serialize将照顾儿童财产.假设您有一个名为Profession的类,就像这样

public class Profession
{
    public string ProfessionName { set; get; }
}
Run Code Online (Sandbox Code Playgroud)

并且您的PersonViewModel具有类型的属性 Profession

public class PersonViewModel
{
    //other properties
    public Profession Profession { set; get; }
    public PersonViewModel()
    {
        if (Profession == null)
            Profession = new Profession();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果从视图中填充这些数据,您将在HttpPost Action方法中获取这些数据.

在此输入图像描述


Kam*_*yar 9

var myData = {
              Parameter1: $("#someElementId").val(),
              Parameter2: $("#anotherElementId").val(),
              ListParameter: { /* Define IEnumerable collections as json array as well */}
              // more params here
             }  
$.ajax({
    url: 'someUrl',
    type: 'POST',
    dataType: "json",
    contentType: 'application/json',
    data: JSON.stringify(myData)
});  


[HttpPost]
public JsonResult Create(CustomViewModel vm)
{
    // You can access your ViewModel like a non-ajax call here.
    var passedValue = vm.Parameter1;
}
Run Code Online (Sandbox Code Playgroud)

您还可以序列化整个表单并将其传递给控制器​​的操作方法.在你的ajax电话:

data: $('form').serialize()
Run Code Online (Sandbox Code Playgroud)