简体   繁体   English

ASP.NET MVC JSON将HTML表单发布到视图?

[英]ASP.NET MVC JSON Post a HTML Form to a View?

I have the following code: 我有以下代码:

jQuery: jQuery的:

$.ajax({
    url: '/personcontroller/getperson',
    cache: false,
    type: "POST",
    data: $('#person').serialize(),
    success: function(data) {
      alert('yay');
    }
    });
});

Controller: 控制器:

public ActionResult getPerson(Person person)
{
    return new Json(person);
}

Html Form/Spark: Html Form / Spark:

<form id="person">
   <input id="person.Id" type="hidden" value="${ViewData.Model.Person.Id}" />
   <input id="person.Name" value="${ViewData.Model.Person.Name}"></input>
   <input id="person.Age" value="${ViewData.Model.Person.Age}"></input>
   <input value="${ViewData.Model.Person.Gender}"></input>
</form>

When I POST the ajax call with the form, and put a break point in my action. 当我用表单发布ajax调用时,在我的操作中放置一个断点。 The person object is not being populated with the input values, I feel like I am overlooking something really simple... Can you please point it out to me :| 人物对象没有填充输入值,我觉得我忽略了一些非常简单的事情......你能不能指出我:

Inputs need a name attribute to post correctly. 输入需要name属性才能正确发布。 You should add a name attribute that matches the Id. 您应该添加与Id匹配的name属性。

<form id="person">
   <input id="person.Id" name="person.Id" type="hidden" value="${ViewData.Model.Person.Id}" />
   <input id="person.Name" name="person.Name" value="${ViewData.Model.Person.Name}"></input>
   <input id="person.Age" name="person.Age" value="${ViewData.Model.Person.Age}"></input>
</form>

You should use: 你应该使用:

public ActionResult getPerson([Bind(Prefix="person")]Person person)

EDIT 编辑

And as Michael Gattuso noticed, you should populate name property. 正如迈克尔加图索注意到的那样,你应该填充名称属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM