Asp.net mvc 2 ASP.Net MVC 2-更好的字典模型绑定<;int,int>;

Asp.net mvc 2 ASP.Net MVC 2-更好的字典模型绑定<;int,int>;,asp.net-mvc-2,dictionary,modelbinders,duplicates,Asp.net Mvc 2,Dictionary,Modelbinders,Duplicates,在某些特殊情况下,您需要一个文本框列表(用于处理n-n关联),其id在运行前是未知的。 大概是这样的: // loop on the templates foreach(ITemplate template in templates) { // get the value as text int val; content.TryGetValue(template.Id, out val); var value = ((val >

在某些特殊情况下,您需要一个文本框列表(用于处理n-n关联),其id在运行前是未知的。 大概是这样的:

// loop on the templates
foreach(ITemplate template in templates)
{
        // get the value as text
        int val;
        content.TryGetValue(template.Id, out val);
        var value = ((val > 0) ? val.ToString() : string.Empty);

        // compute the element name (for dictionary binding)
        string id = "cbts_{0}".FormatMe(template.Id);
%>
        <input type="text" id="<%= id %>" name="<%= id %>" value="<%= value %>" />
        <label for="<%= id %>"><%= template.Name %></label>
        <br />
在这个特定的示例中,我希望将计数与我的一些“模板”相关联

在ASP.Net MVC 1中,我编写了一个Dictionary ModelBinder,使其具有清晰直观的HTML。 它允许这样的事情:

// loop on the templates
foreach(ITemplate template in templates)
{
        // get the value as text
        int val;
        content.TryGetValue(template.Id, out val);
        var value = ((val > 0) ? val.ToString() : string.Empty);

        // compute the element name (for dictionary binding)
        string id = "cbts_{0}".FormatMe(template.Id);
%>
        <input type="text" id="<%= id %>" name="<%= id %>" value="<%= value %>" />
        <label for="<%= id %>"><%= template.Name %></label>
        <br />
这太棘手了。 我将很快需要多次使用这种绑定,并且可能会让一些开发人员在应用程序上工作

问题:

  • 你知道一个更好的方法吗

我需要的是IMO,它是一个字典的模型绑定器,它允许一个更好的HTML,并且不考虑所有的值。

< P>你可以在MVC 2中继续使用你的MVC 1模型绑定器。您必须做的最大更改是,您的模型绑定器不应与IValueProvider冲突,而应直接与Request.Form冲突。您可以枚举该集合,并执行特定场景所需的任何逻辑


IValueProvider接口的目的是提供数据来源的抽象,并用于通用绑定器(如DefaultModelBinder)。由于不能保证数据是可枚举的,因此IValueProvider本身不能是IEnumerable。但是在您的特定情况下,如果您有一个特定场景的特定绑定器,并且已经知道数据来自表单,则不需要进行抽象。

我相信本文将有助于-


简而言之,解决方案是模仿MVC 2-3中的MVC 1 ValueProvider。

谢谢您的建议。有时回到基础是关键,很明显你看不到它。。。
int counter= 0;
// loop on the templates
foreach(ITemplate template in templates)
{
        // get the value as text
        int val;
        content.TryGetValue(template.Id, out val);
        var value = ((val > 0) ? val.ToString() : string.Empty);

        // compute the element name (for dictionary binding)
        string id = "cbts_{0}".FormatMe(template.Id);
        string dictKey = "cbts[{0}].Key".FormatMe(counter);
        string dictValue = "cbts[{0}].Value".FormatMe(counter++);
%>
        <input type="hidden" name="<%= dictKey %>" value="<%= template.Id %>" />
        <input type="text" id="<%= id %>" name="<%= dictValue %>" value="<%= value %>" />
        <label for="<%= id %>"><%= template.Name %></label>
        <br />
public ActionResult Save(int? id, Dictionary<int, int> cbts)
{
    // clear all errors from the modelstate
    foreach(var value in this.ModelState.Values)
        value.Errors.Clear();