Skip to main content
 首页 » 编程设计

c#之MVC ajax 形式的嵌套对象在 Controller 中捕获

2024年02月03日35cloudgamer

在 MVC3 Razor 中:

我正在尝试使用来自多个对象的字段动态地创建一个表单。但出于某种原因,我在 Controller 中获得的数据不包含输入值。

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 中,名称和地址应该是属性。 The default model binder only works on properties .

public class FormViewModel 
{ 
    public Name Name {get;set;} 
    public Address Address {get;set;} 
}