从视图中检索数据,我应该使用模型绑定器吗?

时间:2011-04-01 12:02:46

标签: c# asp.net-mvc modelbinders

我有点迷失在这里因为我没有真正看过模型粘合剂,所以如果可能的话,可以告诉我,如果我实际上正在考虑我的问题... :)如果我的代码是方式,请指教...

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-在我的repo / business层中我设置值并返回要呈现的视图的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>
<% } %>

问题:通过帖子检索结果的最佳方法是什么?如果有错误,我需要将错误发送回视图......

注意:我做了什么 - &gt;

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

Custom Model binder从表单集合中获取值并转换为正确的类型 - 这是正确的吗?这样做的最好方法是什么?我觉得我的事情过于复杂......

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;
 }
}

1 个答案:

答案 0 :(得分: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...
}

无需任何型号粘合剂。编辑器模板将负责为输入字段生成专有名称,以便正确绑定它们。

相关问题