1

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& ...
Jez
  • 404
  • 1
  • 6
  • 16

1 Answers1

0

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

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Thanks for your reply. Sorry, no form element as this is an AJAX callback. I'm using JQuery's .serialize() and on inspection of the data being sent from the client, all looks ok. There are no duplicated values. I have about 30 or so hidden controls in a container div which are all binding correctly apart from the dictionary. – Jez Jun 09 '13 at 08:22
  • You are right, the issue is elsewhere. So, now I have the **answer** for you;) – Radim Köhler Jun 09 '13 at 09:44
  • Well, that's the easy answer I guess. The static helper AnonymousObjectToHtmlAttributes implements IDictionary which leaves it up to the client to strongly type the attribute values. Thanks for your input Radim. – Jez Jun 09 '13 at 16:02