5

i'm trying to recreate something i did back in winforms days with html data- attributes in mvc.

you could set an attribute on a form control using this:

txtTest.Attributes.Add("data-myattribute", "my value");

and then read it back once the form had been posted using:

txtTest.Attributes["data-myattribute"]

adding the attributes in mvc is a breeze:

@Html.TextBoxFor(m => m.FirstName, new { data_myattribute = "my value" })

just can't figure out how to read them in the action result once the form has been posted?!

been searching around and whilst i can find loadsa posts on how to set data- attribute values and read them in javascript, i can't find anything that'll tell me how to get them back in the code...

anyone out there know the magic answer?!

jakewilliamson
  • 213
  • 3
  • 8

1 Answers1

3

Data attributes are not included in the data that's posted with the form, so there is no way to read them in your controller action. Try using a hidden field instead:

<input type="hidden" name="FirstNameAttribute" value="my value" />

This'll bind back to a model property:

public string FirstNameAttribute { get; set; }
Ant P
  • 24,820
  • 5
  • 68
  • 105
  • darn it! had a feeling that was the case... unfortunately, i need to set the value dynamically on each list element of a select control... back to the drawing board on that one then! thank you for the reply ;) – jakewilliamson Apr 30 '14 at 10:25
  • You can still use this approach - just use a data attribute and update the value of the hidden field with Javascript each time an option is selected. HTH. – Ant P Apr 30 '14 at 10:27
  • this is very true... but (throwing yet another blocker in!) i've gotta code up this particular site with js fallbacks (bit of a mare). i really don't wanna get into the realms of piping the value e.g. '43|my value' as it feels way hacky but it's the only solution i can think of right now... – jakewilliamson Apr 30 '14 at 10:35
  • Yeah, that's a tough one - the only other thing I could suggest would be to have a dictionary in your model where the key is the option value and the value is the attribute. Then create a hidden field for every option, then look it up in the dict on postback. So for each hidden field, the name would be `MyDictionary[optionValue]` and the value would be `myAttributeValue`. Binding the dictionary is pretty straightforward: http://stackoverflow.com/questions/5191303/asp-net-mvc-binding-to-a-dictionary/18683004#18683004 – Ant P Apr 30 '14 at 10:50
  • interesting idea - gonna give it a go, see if it works – jakewilliamson May 01 '14 at 08:25