TextBoxFor - Showing Wrong Value

2019-01-26 12:14发布

问题:

Ok, I've got a weird one here. I know the value is being passed to the property correctly as this works fine:

@Html.TextBox("Foo", Model.Foo, new { @class = "bar" })

Now if i do this:

@Html.TextBoxFor(m => m.Foo, new { @class = "bar" })

It show's an incorrect value. I have absolutely no idea where this value is coming from. For some pages, it shows a lowercase version of what it should be, other times, it shows the value of the textbox next to it. I'm baffled. It's the only textbox that does this. I also have a razor helper on the page that uses this exact value to display the heading of the page, and that shows correctly.

I don't mind using @Html.TextBox() for this particular one, but I'd like to get the bottom of this.

Anyone else had anything random like this happen? I have quite a few controls on this particular page and it's the only one this happens to.

回答1:

Oh jeez... I just found the culprit. It's the url routing value! lol

In my global file, I had {something}/{whatever}/{id}/{foo}, {foo} being an optional parameter there just to make the page url look human friendly.

It is interesting that the expression used in TextBoxFor is pulling from the URL rather than the viewmodel. I would have thought it'd read the model before going to the URL? Even intellisense pulls from the model. Is this some sort of a bug?

Note to self: Always make sure properties have different names!

Hopefully this experience will help others.



回答2:

Could you post some code from the View where this is happening, as well as of the Model? It is probably something in there as opposed to the @Html.TextBoxFor() method.



回答3:

This happened to me when doing an ajax call to create an entity and upon success reloaded the entity list with a partial view. During reload the textboxes in the view were taking the value of the new entity added for the all items in the list. Adding ModelState.Clear(); to the server code fixed it.