2013-05-04 103 views
2

我有一個自定義類MVC4傳遞自定義視圖模型回控制器動作

public class BloggerViewModel 
{   
    public Person Blogger; 
    public List<BloggerWebsite> BloggerWebsites; 
} 

那我傳遞到視圖

[HttpGet] 
    public ActionResult Edit(int id) 
    { 
     blogger = GetById(id);    
     var WebSites = GetBloggersWebsites(Id);    
     var BloggerViewModel = new BloggerViewModel(); 
     BloggerViewModel.Blogger = blogger; 
     BloggerViewModel.BloggerWebsites = WebSites; 
     return View(BloggerViewModel); 
    } 

然後,當我回發到編輯動作

[HttpPost] 
public ActionResult Edit(BloggerViewModel entity) 
{ 
    return View(entity); 
} 

entity爲空。

我的看法是這樣的(我拿出配發,你並不需要看到的代碼。如大多數文本框的綁定)

@model Bloginect.Model.Models.BloggerViewModel 

<h2>Edit</h2> 

@using (Html.BeginForm()) { 
@Html.ValidationSummary(true) 

<fieldset> 
    <legend>Person</legend> 

    @Html.HiddenFor(model => model.Blogger.Id) 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Blogger.FirstName) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Blogger.FirstName) 
     @Html.ValidationMessageFor(model => model.Blogger.FirstName) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Blogger.LastName) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Blogger.LastName) 
     @Html.ValidationMessageFor(model => model.Blogger.LastName) 
    </div> 

     <div class="editor-field"> 

      @if (Model.BloggerWebsites[0].Website != null) 
      { 
       Html.EditorFor(model => model.BloggerWebsites[0].Website); 
      } 
      else 
      { 
       @Html.TextBox("Website1") 
      } 

     </div> 

     <div class="editor-field"> 
      @if (Model.BloggerWebsites[1].Website != null) 
      { 
       Html.EditorFor(model => model.BloggerWebsites[0].Website); 
      } 
      else 
      { 
       @Html.TextBox("Website2") 
      } 
     </div> 

     <div class="editor-field"> 
      @if (Model.BloggerWebsites[2].Website != null) 
      { 
       Html.EditorFor(model => model.BloggerWebsites[0].Website); 
      } 
      else 
      { 
       @Html.TextBox("Website3") 
      }   
     </div> 

    <p> 
     <input type="submit" value="Save" /> 
    </p> 
</fieldset> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

有什麼我做錯了?我已經檢查了一些關於此類問題的其他答覆,他們沒有回答我的問題。

+0

您正在渲染'Html.EditorFor(model => model.BloggerWebsites [0] .Website);'三次,更改索引並檢查是否可以解決您的問題。 – 2013-05-04 09:49:55

+0

@VimalStan恐怕沒有工作 – 2013-05-04 09:53:12

+0

你正在看的是一個嵌套的viewmodel.you可能需要爲person創建一個單獨的viewmodel並將其嵌套在BloggerViewModel中 – 2013-05-04 09:53:18

回答

0

您必須使用編輯器處理對嵌套模型屬性的綁定,有關如何執行此操作的很好示例可以參見here

相關問題