Search code examples
c#asp.net-mvcasp.net-mvc-4html-helperhtml.hiddenfor

Prevent use of MVC's HiddenFor function


I have the problem documented here and here and here and especially here where, in an ASP.NET MVC4 view, the html helper function @Html.HiddenFor(m => m.ID) will use the "wrong" data and cause data corruption.

This is a massive problem, and the accepted "solution" is to simply be aware of this and design around it. I think that is a poor solution. (Incidentally, we use something like this instead: <input type="hidden" value="@Model.ID" />)

Every few months, I or a colleague forget and use that html helper, and all hell breaks loose before we track down the problem... once again.

How can I eliminate the use of this function, to avoid mistakes in the future?
- it's not our code, so we cannot mark it with [Obsolete]
- we can override the HtmlHelper, but that's a lot of work just to eliminate one function
- can I write a unit test to pick out this code from the view? (and fail test if that call is detected)
- other ideas?


Solution

  • This is not a "problem", it's the way it's supposed to work. And it's not just HiddenFor that does it, every helper will do it. it's the way MVC is designed to work. The fact that you don't seem to understand how MVC works is the real problem.

    This is part of the ModelState subsystem, and you are wise to know exactly how this works. Yes, it's not always intuitive, but it's far better that you actually know how things work than to pretend they don't exist, because you'll end up bitten in other ways with other helpers.

    But, if you choose otherwise, I would suggest configuring StyleCop to deal with this issue