2011-04-01 49 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

相关问题