user895400
user895400

Reputation: 368

input type="hidden" vs htmlhelper strange issue

I spent an hour trying to figure out why the value in my hidden field was a different one than the one I was expecting. As a last ditch effort I switched it to a hidden field and it started rendering as the one I was expecting. Why would that happen??

Some context is that the ID that the one using the htmlhelper is using is the same one in the querystring ID parameter.

 // renders 123
  @using (Html.BeginForm()){
         <input type="hidden" name="id" value="@Model.ID" />
  }

vs

// renders 456
@using (Html.BeginForm()){
         @Html.Hidden("id", Model.ID)
}

Upvotes: 4

Views: 4115

Answers (1)

TIHan
TIHan

Reputation: 632

I believe this is part of the naming convention of MVC. This has happened to me as one of my Properties of a Model was "Title", and it conflicted with the ViewBag.Title. It started displaying the ViewBag.Title instead of the actual Model's Title.

I believe this only happens when you explicitly state "Model.ID" in the HtmlHelper. It looks at the property name "ID", then looks through the ViewContext and finds query string "ID" and uses it.

It doesn't use the query string "ID" for the one that doesn't use the HtmlHelper because it doesn't look through the ViewContext to find that name; it simply puts whatever the value is from the Model. HtmlHelpers generally look at the ViewContext and figure out what value to use just based on the Property Name rather than where it exactly came from.

If you want to use an HtmlHelper, try this and see what it does:

@Html.HiddenFor(model => model.ID)

Upvotes: 1

Related Questions