Frage

I have a model binding issue with an html helper I'm writing. I have declared a property on my Model to handle html attributes, In short;

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

I then render the following html as in Scott Hanselman's post;

<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" />

But on callback the DefaultModelBinder creates the value as a string array, such that the next time I render my html value;

_attribute.Value.ToString()

I get the following HTML;

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

Which is obviously a default ToString representation of a string array. The value is the first element!!

It seems the default model binder is confused about the value type parameter being declared as object for the Dictionary. I was sure I was following convention by declaring my htmlAttributes as Dictionary<string,object>, as I observed in the Html Helpers source code. Am I missing something obvious here?

EDIT:

Just an update to give more info. The binding issue I'm seeing is as a result of an JQuery AJAX post $.post callback, where the data is being serialized using JQuery's .serialize(); On inspecting the data being sent, again all looks to be in order.

HtmlAttributes%5B0%5D.Key=align&HtmlAttributes%5B0%5D.Value=center& ...
War es hilfreich?

Lösung

Your code seems to be correct. Check the <form> sent to the server. There most likely would be doubled name HtmlAttributes[0].Value

<input name="HtmlAttributes[0].Value" ... ... <input name="HtmlAttributes[0].Value" ...

That ends up with the not a signle but multiple value ... i.e. System.String[]

EDIT: the issue is

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

into

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

The value must be of type string to force ModelBinder to correclty covnert raw value

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top