2011-04-01 38 views
3

我有點迷失在這裏,因爲我沒有真正看着模型粘合劑,所以如果可能的話,可以告訴我,如果我真的正確地考慮我的問題...... :),如果我的代碼的方式,請指教。 ..從視圖中檢索數據,我應該使用模型綁定器嗎?

1 -I有一個包含「自定義字段」各自的名稱和其他屬性,即一個DTO類:

Public Class CustomFields 
{ 
public string Name {get;set;} 
public string Description {get;set;} 
public string FieldType {get;set;} 
public string Value {get;set;} 
} 

2 - 在我的回購/業務層,我設置的值,並返回ICollection呈現視圖

3-視圖使用foreach顯示字段

<% foreach (var item in Model) {%> 
    <div class="editor-label"> 
     <%= Html.Label(item.Name) %> 
    </div> 
    <div class="editor-field"> 
     <%= Html.TextBox(item.Name, item.Value)%> 
    </div> 
<% } %> 

問題:通過帖子檢索結果的最佳方法是什麼?如果有錯誤,我需要將錯誤發送回視...

注:我做了什麼 - >

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Index([ModelBinder(typeof(CustomModelBinder))] ICollection<CustomFields> Fields) 
{ 
//code here... 
} 

定義模型粘合劑會從形式收藏價值和轉換中到正確的鍵入 - 這是正確的嗎?最好的方法來做到這一點?我覺得我過於複雜的東西...

public class CustomModelBinder : IModelBinder 
{ 
public object BindModel(ControllerContext controllerContext, 
ModelBindingContext bindingContext) 
{ 

    var fields = new List<CustomFields>(); 

    var formCollection = new FormCollection(controllerContext.HttpContext.Request.Form); 

    foreach (string _key in formCollection) 
    { 
    if (_key.Contains("_RequestVerificationToken")) 
     break; 

    fields.Add(new CustomFields { Name = _key, 
    Value = formCollection.GetValue(_key).AttemptedValue }); 
    } 
    return fields; 
} 
} 

回答

3

一切都是完美的,直到第3步,你在視圖中提到foreach循環。這就是我停止使用編輯器模板的地方。

<%= Html.EditorForModel() %> 

和將要呈現的模型集合中的每個元素(~/Views/Shared/EditorTemplates/CustomFields.ascx)相應的編輯模板中:簡單

<div class="editor-label"> 
    <%= Html.LabelFor(x => x.Name) %> 
</div> 
<div class="editor-field"> 
    <%= Html.TextBoxFor(x => x.Name) %> 
</div> 
<div class="editor-field"> 
    <%= Html.TextBoxFor(x => x.Value) %> 
</div> 
<div class="editor-field"> 
    <%= Html.TextBoxFor(x => x.Description) %> 
</div> 
<div class="editor-field"> 
    <%= Html.TextBoxFor(x => x.FieldType) %> 
</div> 

則:

所以通過更換循環在您的視圖
[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Index(IEnumerable<CustomFields> fields) 
{ 
    //code here... 
} 

不需要任何模型粘合劑。編輯器模板將負責爲輸入字段生成正確的名稱,以便正確綁定它們。

+0

謝謝,從未想過編輯模型! :) – Haroon 2011-04-01 12:21:06

相關問題