如何将jquery.post中的数据发送到使用ViewModel作为参数的mvc控制器?
我正在用asp.net mvc编写应用程序。 我有控制器动作,它使用一些ViewModel作为参数。 如何使用jquery post将表单数据发送到该mvc控制器。
$.post("Yourcontroller/YourAction", { FirstName : $("#txtFirstName").val(), LastName : $("#txtLastName") } ,function(data){ //do whatever with the response });
您传递的ViewModel属性名称和参数应该相同。 即:您的视图模型应该有2个名为FirstName
和LastName
属性,如他的
public class PersonViewModel { public string FirstName { set;get;} public string LastName { set;get;} // other properties }
并且您的Post动作方法应该接受PersonViewModel
类型的参数
[HttpPost] public ActionResult YourAction(PersonViewModel model) { //Now check model.FirstName }
或者,如果您的视图是强类型的PersonViewModel,您只需使用jQuery serialize
方法将序列化表单发送到action方法
$.post("Yourcontroller/YourAction", $("#formId").serialize() ,function(data){ //do whatever with the response });
编辑:根据评论
Serialize
也会处理Child属性。 假设您有一个名为Profession的类,就像这样
public class Profession { public string ProfessionName { set; get; } }
您的PersonViewModel具有Profession
类型的属性
public class PersonViewModel { //other properties public Profession Profession { set; get; } public PersonViewModel() { if (Profession == null) Profession = new Profession(); } }
如果从视图中填充这些数据,您将在HttpPost Action方法中获取这些数据。
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; }
您还可以序列化整个表单并将其传递给控制器的操作方法。 在你的ajax电话:
data: $('form').serialize()