asp.net-mvcasp.net-mvc-4razor-2

ASP.NET MVC 4 override emitted html name and id


I'm trying to change the emitted name of the html input created by @Html.HiddenFor.

The code I'm using this:

@Html.HiddenFor(e => e.SomeProperty, new { @id = "some_property", @name = "some_property" }

Now this works for the id, however it doesn't work for the name. Now I don't really care for the id now, I need the name to change, because that's the one that get's posted back to the target server.

Is there

Or am I stuck to do a plain <input ...> by hand?


Solution

  • You need to use the Html.Hidden (or write out the <input ...> by hand) instead of the Html.HiddenFor

    @Html.Hidden("some_property", Model.SomeProperty, new { @id = "some_property" })
    

    The goal of the strongly typed helpers (e.g the one which the name end "For" like HiddenFor) is to guess the input name for you from the provided expression. So if you want to have a "custom" input name you can always use the regular helpers like Html.Hidden where you can explicitly set the name.

    The answer from unjuken is wrong because it generates invalid HTML.

    Using that solution generates TWO name attributes:

    <input  Name="some_property"  name="SomeProperty" id="some_property" type="hidden" value="test" /> 
    

    So you will have Name="some_property" AND name="SomeProperty" which is INVALID HTML because an input can only have ONE name attribute! (although most browers happen to take the first Name="some_property" and don't care about the second one...)