嵌套的对象在MVC ajax形式捕捉在控制器
本文关键字:控制器 ajax 对象 MVC 嵌套 | 更新日期: 2023-09-27 18:07:10
In MVC3 Razor:
我试图创建一个表单,动态地,使用多个对象的字段。但是由于某些原因,我在控制器中获得的数据不包含输入值。
FormViewModel.cs
namespace DynamicForm.Models
{
public class FormViewModel
{
public Name name = new Name();
public Address address = new Address();
public FormViewModel()
{
}
}
public class Name
{
[Required()]
public String first { get; set; }
[Required()]
public String last { get; set; }
public Name()
{
first = "";
last = "";
}
}
public class Address
{
public String street1 { get; set; }
public String street2 { get; set; }
public Address()
{
street1 = "";
street2 = "";
}
}
}
FormController.cs
[HttpPost()]
public ActionResult Save(FormViewModel toSave)
{
return View();
}
index.cshtml:
@using DynamicForm;
@using DynamicForm.Models;
@model FormViewModel
@{
ViewBag.Title = "Form";
}
<h2>Form</h2>
@using (Html.BeginForm("Save", "Form"))
{
@Html.TextBoxFor(m => m.address.street1)
@Html.TextBoxFor(m => m.address.street2)
@Html.TextBoxFor(m => m.name.first)
@Html.TextBoxFor(m => m.name.last)
<input type="submit" value="Send" />
}
关于为什么数据没有被填充到FormViewModel对象中的任何想法?
在FormViewModel中,name和address应该是属性。默认的模型绑定器只作用于属性。
public class FormViewModel
{
public Name Name {get;set;}
public Address Address {get;set;}
}