2010-07-12 62 views
0

假設我在一個視圖模型已通過與多個地址如何使用TextBoxFor更新

我期待寫一個視圖像這樣(簡體)

一個人記錄的關係的許多方面
<% foreach (var addr in Model.PERSON.ADDRESSES) { %> 
    <li> 
     <%: Html.TextBoxFor(m => addr.Add1)%> 
    </li> 
<% } %> 

然而,每個生成的Textbox都具有相同的ID和Name屬性,並且毫不奇怪,控制器代碼無法對模型進行任何更新。

[HttpPost] 
public ActionResult Edit(int id, FormCollection collection) 
{ 
    MyViewModel viewmodel = GenerateViewModel(id); 
    try 
    { 
     UpdateModel(viewmodel); 
     _MyRepository.Save(); 
     return View(viewmodel); 
    } 
    catch 
    { 
     return View(viewmodel); 
    } 
} 

我在猜測我正在討論這個錯誤的方法:任何線索將不勝感激!

回答

0

您可以使用編輯器模板。

控制器:

public ActionResult Index() 
{ 
    var model = new MyViewModel(); 
    model.PERSON = FetchPerson(); 
    return View(model); 
} 

[HttpPost] 
public ActionResult Edit(MyViewModel model) 
{ 
    _MyRepository.Save(model); 
    return View(model); 
} 

查看:爲地址

<ul> 
    <%: Html.EditorFor(x => x.PERSON.ADDRESSES) %> 
</ul> 

編輯模板(~/Shared/Views/EditorTemplates/ADDRESS.ascx):

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeNs.ADDRESS>" %> 

<li> 
    Street: <%: Html.EditorFor(x => x.Street) %> 
</li> 
+0

這幾乎是正確的。我認爲你的第一個ActionResult應該是Edit()?因此,我得到控制呈現與似是而非的名字 - PERSON.ADDRESSES [1] .Street但試圖保存時出現錯誤 System.InvalidOperationException未處理用戶代碼 消息= EntityCollection已被初始化。只應調用InitializeRelatedCollection方法來在對象圖的反序列化過程中初始化新的EntityCollection。 (from myModel.Designer.cs EntityCollection

ADDRESSES setter) – Andiih 2010-07-13 09:13:05

+0

我的錯誤也在這裏解決stackoverflow.com/questions/1064998/...我有一個類似的viewmodel實體圖和一些下拉列表。可悲的是,沒有發佈的解決方案似乎工作(對我或OP) – Andiih 2010-07-13 13:23:54