Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC : Changing model's properties on postback

Tags:

asp.net-mvc

I've been playing with ASP.NET MVC and ran into something I can't figure out.

Suppose I have an object like this :

public class TestObject
{
    public string Name { get; set; }
    public int Age { get; set; }
}

And a view page (Create.aspx) like this :

<form action="/Create" method="post">
    <p>
        <%=Html.TextBox("Name") %>
    </p>
    <p>
        <%=Html.TextBox("Age")%>
    </p>
</form>

And on my controller I have these actions :

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create()
{
    return View(new TestObject { Name = "DefaultName", Age = 10 } );
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(TestObject o)
{
    o.Name = "ChangedNameToSomethingElse";
    o.Age = 15;
    return View(o);
}

The Html.TextBox() method always genereates the textboxes with the default values, even after the postback, where the object is passed back with different properties on its values. Now, granted, I can't think of a real world example why I'd want to do such a thing but I still don't understand why I always end up having textboxes populated with the model's values that were set on the Create action with the AcceptVerbs(HttpVerbs.Get) attribute.

Note : I've tried Html.TextBox("Name", Model.Name) but the result is still the same. And I verified that the Create action with AcceptVerbs(HttpVerbs.Post) actually runs, by passing a value via ViewData to the View. Also, the udated value is displayed when I output the value with <%=Model.Name %> but again, not on the textbox.

Is there something obvious I'm missing, or is there a reasoning behind this behaviour?

like image 709
Çağdaş Tekin Avatar asked Apr 01 '09 22:04

Çağdaş Tekin


1 Answers

If you bind the result of a post request through the declaration of the method or by UpdateModel or TryUpdateModel to an object such as TestObject, a property called ModelState will get filled in with these values. The HTML helpers such as Textbox will always bind to modelstate over an explicitly passed model object.

like image 81
dpen2000 Avatar answered Sep 28 '22 03:09

dpen2000