如何将 jquery.post 中的数据发送到使用 ViewModel 作为参数的 mvc 控制器? [英] How to send data in jquery.post to mvc controller which use ViewModel as parameter?

查看:31
本文介绍了如何将 jquery.post 中的数据发送到使用 ViewModel 作为参数的 mvc 控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

});

您的 ViewModel 属性名称和我们传递的参数应该相同.即:你的视图模型应该有 2 个属性,叫做 FirstNameLastName 就像他的

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

}

并且您的 Post 操作方法应该接受 PersonViewModel

And your Post action method should accept a parameter of type PersonViewModel

[HttpPost]
public ActionResult YourAction(PersonViewModel model)
{
  //Now check model.FirstName 
}

或者,如果您的视图是强类型到 PersonViewModel,您可以简单地使用 jQuery serialize 方法将序列化的表单发送到操作方法

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

});

根据评论

Serialize 也会处理 Child 属性.假设你有一个名为 Profession 的类,就像这样

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; }
}

并且你的 PersonViewModel 有一个 Profession

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();
    }
}

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

You will get these data in your HttpPost Action method, if you fill that from your view.

这篇关于如何将 jquery.post 中的数据发送到使用 ViewModel 作为参数的 mvc 控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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