HtmlAttributes字典没有正确绑定

时间:2013-06-08 09:49:06

标签: asp.net-mvc asp.net-mvc-4 html-helper model-binding defaultmodelbinder

我有一个与我正在编写的html帮助器的模型绑定问题。我在我的模型上声明了一个属性来处理html属性,简而言之;

public IDictionary<string,object> HtmlAttributes { get; set; }

然后我在Scott Hanselman's post;

中呈现以下html
<input type="hidden" id="HtmlAttributes[0]_Key" name="HtmlAttributes[0].Key" value="align" />
<input type="hidden" id="HtmlAttributes[0]_Value" name="HtmlAttributes[0].Value" value="center" />

但是在回调时,DefaultModelBinder会将值创建为字符串数组,以便下次渲染我的html值时;

_attribute.Value.ToString()

我得到以下HTML;

<td align="System.String[]"></td>

这显然是字符串数组的默认ToString表示。该值是第一个元素!!

似乎默认的模型绑定器对于声明为Dictionary的对象的值类型参数感到困惑。我确信我遵循惯例,将htmlAttributes声明为Dictionary<string,object>,正如我在Html Helpers源代码中所观察到的那样。我错过了一些明显的东西吗?

编辑:

只是提供更多信息的更新。我看到的绑定问题是JQuery AJAX post $.post回调的结果,其中数据是使用JQuery的.serialize()序列化的。在检查正在发送的数据时,所有数据看起来都是有序的。

HtmlAttributes%5B0%5D.Key=align&HtmlAttributes%5B0%5D.Value=center& ...

1 个答案:

答案 0 :(得分:0)

您的代码似乎是正确的。检查发送到服务器的<form>。最有可能是名称加倍HtmlAttributes[0].Value

<德尔> <input name="HtmlAttributes[0].Value" ... ... <删除> <input name="HtmlAttributes[0].Value" ...

不是一个信号结束但是多个值......即System.String[]

编辑:问题是

更改公开IDictionary<string,object> HtmlAttributes { get; set; }

进入

IDictionary<string,string> HtmlAttributes { get; set; }

该值必须为 string 类型,以强制ModelBinder更正为covnert原始值

相关问题