问题描述
我写与asp.net MVC应用程序。我有控制器动作,使用一些视图模型作为参数。如何用jQuery邮寄表单数据到MVC控制器。
$后(Yourcontroller / YourAction,{姓:$(#txtFirstName)VAL() ,名字:$(#txtLastName)},功能(数据){
//做任何的回应});
您的ViewModel属性名称和我们传递应该是相同的参数。例如:您的视图模型应该有2个属性叫做姓
和姓
喜欢他
公共类PersonViewModel
{
公共字符串名字{集;获取;}
公共字符串名字{集;获取;}
//其他属性}
和您的帖子的操作方法应该接受类型的参数 PersonViewModel
[HttpPost]
公众的ActionResult YourAction(PersonViewModel模型)
{
//现在检查model.FirstName
}
另外,如果你的看法是强类型的PersonViewModel,你可以简单的序列化形式使用jQuery 发送到操作方法连载
法
$。员额(Yourcontroller / YourAction,$(#formId)。序列化(),功能(数据){
//做任何的回应});
编辑:按照注释
序列化
将照顾孩子财产为好。假设你有一个叫做行业如该类
公共类专业
{
公共字符串ProfessionName {设置;得到; }
}
和您的PersonViewModel有一个类型的属性行业
公共类PersonViewModel
{
//其他属性
公共事业行业{集;得到; }
公共PersonViewModel()
{
如果(职业== NULL)
职业=新的职业();
}
}
您会在你的HttpPost Action方法得到这些数据,如果你填写,从您的看法。
I am writing application with asp.net mvc. I have controller with action, which use some ViewModel as parameter. How to send form data with jquery post to that mvc controller.
$.post("Yourcontroller/YourAction", { FirstName : $("#txtFirstName").val(), LastName : $("#txtLastName") } ,function(data){
//do whatever with the response
});
Your ViewModel Property names and Parameter we are passing should be same. Ie : Your view model should have 2 properties called FirstName
and LastName
like his
public class PersonViewModel
{
public string FirstName { set;get;}
public string LastName { set;get;}
// other properties
}
And your Post action method should accept a parameter of type PersonViewModel
[HttpPost]
public ActionResult YourAction(PersonViewModel model)
{
//Now check model.FirstName
}
Alternatively, If your view is strongly typed to the PersonViewModel, you can simply send the serialized form to the action method using jQuery serialize
method
$.post("Yourcontroller/YourAction", $("#formId").serialize() ,function(data){
//do whatever with the response
});
EDIT : As per the comment
Serialize
will take care of the Child property as well. Assume you have a class called Profession like this
public class Profession
{
public string ProfessionName { set; get; }
}
And your PersonViewModel has a property of type Profession
public class PersonViewModel
{
//other properties
public Profession Profession { set; get; }
public PersonViewModel()
{
if (Profession == null)
Profession = new Profession();
}
}
You will get these data in your HttpPost Action method, if you fill that from your view.
这篇关于如何jquery.post到使用视图模型作为参数MVC控制器发送数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!