3

I spotted some strange behavior and wanted to see if anyone else had come across it and if I was being silly or if it was a bug.

When and ID is passed in the URL to a page along with a model wit an ID properties

The view renders out different values for Model.Id

ViewModle example

public int Id { get; set; } - value 2
....

Controller example

    public ActionResult Index(int id)
    {
        // code

        return View(model);
    }

URL looks like - Activity/Index/1 - url id = 1

If I enter the following into my view

@Html.TextBoxFor( x => x.Id)
@Html.TextBoxFor(x => Model.Id)
@Html.TextAreaFor(x => Model.Id)

<p>@Model.Id</P>

I get the following output

Value of Textbox = 1

Value of TextArea = 1 but the value of the

<p> 

tag = 2 - The Id I passed into the view in my ViewModel

I fixed this by renaming the Id field in my ViewModel to TableId

So it seems to me that the Id passed into the url is being used up by the Textbox / Area for and the paragraph finds the value I pass into my ViewModel. Very strange

tereško
  • 58,060
  • 25
  • 98
  • 150
monkeylumps
  • 747
  • 4
  • 10
  • 23
  • This question has been asked a billion times before... see http://stackoverflow.com/questions/10248757/model-property-set-in-controller-not-showing-up-in-view, http://stackoverflow.com/questions/18188737/is-this-by-design-in-mvc-model-binding, http://stackoverflow.com/questions/1434734/asp-net-mvc-dropdownlist-selected-value-problem – Erik Funkenbusch Sep 11 '14 at 17:47

1 Answers1

2

This behavior is by design - though perhaps unintuitive at first.

The built-in html helpers have a priority for what they use to determine a value - ModelState (which would come from binding in the Url) takes precedence over model values.

If you manually clear the modelstate (e.g. in your controller) you will see that the same values are rendered.

E.g.

ModelState.Clear(); //Clears all modelstate.(you can also be more specific 
                    //and only clear specified modelstate values.

See also: ASP.NET MVC’s Html Helpers Render the Wrong Value!

Nathan
  • 10,593
  • 10
  • 63
  • 87
  • This clears up why the HTML.For's are getting a different value but but does not explain why the Raw

    tag is getting a different value. I would expect the behavior to be consistent.

    – monkeylumps Sep 12 '14 at 08:22
  • @monkeylumps `@Model.Id` is _not_ an html helper. In this case, you are directly accessing the model. `@Html.TextBoxFor(x => Model.Id)` is an html helper, so the precedence rules apply. – Nathan Sep 12 '14 at 16:50