2013-06-27 56 views
0

我有一個outerViewModel和兩份的ViewModels,裏面 當我嘗試綁定innermodel我得到空的所有屬性...MVC4嵌套視圖模型綁定不起作用

這裏是代碼:

**Models.cs** 

public class OuterModel 
{ 
    public FirstInnerModel firstInnerModel; 
    public SecondInnerModel secondInnerModel; 
} 

public class FirstInnerModel 
{ 
    public string Title; 
} 

public class SecondInnerModel 
{ 
    public string Title; 
} 

Index.cshtml

  @using (Html.BeginForm("ActivateFirst", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 
     { 

       @Html.ValidationSummary(true) 

       <fieldset> 

        <div class="editor-label"> 
         @Html.LabelFor(model => model.firstInnerModel.Title) 
        </div> 
        <div class="editor-field"> 
         @Html.EditorFor(model => model.firstInnerModel.Title) 
         @Html.ValidationMessageFor(model =>   model.firstInnerModel.Title) 
        </div> 
        <p> 
         <input type="submit" value="Create" /> 
        </p> 
       </fieldset> 
     } 

HomeController.cs

public ActionResult Index() 
    { 
     ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 

     var model = new OuterModel() 
     { 
      firstInnerModel = new FirstInnerModel(), 
      secondInnerModel = new SecondInnerModel() 
     }; 

     return View(model); 
    } 

    [HttpPost] 
    public void ActivateFirst(FirstInnerModel ggg) 
    { 


    } 

ggg.Title返回null ...

有人嗎?幫幫我!

+0

? – James

+0

嗨! :)。 no ... firstInnerModel和secondInnerModel都爲空 – user2355293

+0

您可能需要在表單上爲「OuterModel」設置一個隱藏字段,以便將其傳回控制器。 – James

回答

3

當您提交將被張貼OuterModel到控制器的形式,所以你需要做的是這樣的:如果你在`OuterModel`傳遞給`ActivateFirst`你得到你的數據

[HttpPost] 
    public void ActivateFirst(OuterModel ggg) 
    { 
     var whatever = ggg.FirstInnerModel.Title; 

    }