c# - 从 View 中检索数据,我应该使用模型联编程序吗?

标签 c# asp.net-mvc modelbinders

我在这里有点迷路,因为我没有真正看过模型 Binder ,所以如果可能的话,有人可以告诉我我是否真的正确地考虑了我的问题......:) 如果我的代码是这样,请告诉我...

1 - 我有一个 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 /业务层中,我正在设置值并返回 ICollection 以供 View 呈现

3- View 使用 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>
<% } %>

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

注意:我做了什么-->

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

最佳答案

一切都很完美,直到您在 View 中提到 foreach 循环的第 3 步。这就是我要停下来并改用编辑器模板的地方。因此,将 View 中的循环替换为:

<%= 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...
}

不需要任何模型 Binder 。编辑器模板将负责为输入字段生成适当的名称,以便正确绑定(bind)它们。

关于c# - 从 View 中检索数据,我应该使用模型联编程序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5513091/

相关文章:

c# - 比较 Linq 中的 DateTime 对象

asp.net - 使用 MVC 库在 ASP.NET Web 窗体中进行基于属性的验证?

asp.net-mvc - asp.net mvc : TryUpdateModel return value or ModelState. 是否有效?

asp.net-mvc - ASP.NET MVC 1.0 - 字典的模型绑定(bind)器

asp.net-mvc - ASP.NET MVC Html.RadioButton 异常

asp.net - 在 JavaScript 代码中嵌入常量服务器端标签的最佳方法是什么?

c# - MVC4 无法将对象属性从 AJAX POST 映射到 JSON

c# - WPF 如何确定应该重绘某些内容?我怎么知道?

c# - 内部对象属性更改时自动引发 PropertyChanged

c# - 如何在我的 ASP.Net MVC 5 应用程序的同一页面中编辑和删除 POST 请求