Admir Tuzović
Admir Tuzović

Reputation: 11177

MVC4 TextBoxFor overwritting model property

Say I have a model:

public MyClass
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int ContentId {get;set;}
}

Let's assume I access the action of the controller:

[HttpGet]
public ActionResult Create(int id)
{
    MyClass mc = new MyClass();
    mc.Id = 49;
    mc.ContentId = id;
    mc.Name = "Sample";
    return View("Create", mc);
}

"Create" view is strongly-typed with MyClass, and it has helper @Html.TextBoxFor(x => x.Id).

If I call action by invoking MyController/Create?id=15, textbox will show value 15 instead of 49. MVC will ignore my ID property set in action, and use the one from the query.

I find this rather odd considering this behavior is nowhere documented.

Any good comments on this?

Upvotes: 2

Views: 1962

Answers (3)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93474

This is a common problem and is documented in various places. A good example is here:

http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx

Upvotes: 1

Aviran Cohen
Aviran Cohen

Reputation: 5691

Use ModelState.Clear() at the start of the Action

Upvotes: 8

Jeffrey Lott
Jeffrey Lott

Reputation: 7439

Instead of

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

Use:

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

And see if that gives you the functionality you're looking for.

Upvotes: 1

Related Questions