Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC get a form control data- attribute value in a post ActionResult

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?!

like image 582
jakewilliamson Avatar asked Oct 21 '22 09:10

jakewilliamson


1 Answers

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; }
like image 181
Ant P Avatar answered Oct 23 '22 00:10

Ant P