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;
}
}
謝謝,從未想過編輯模型! :) – Haroon 2011-04-01 12:21:06