ASP.NET MVC:更改模型的回发的属性 [英] ASP.NET MVC : Changing model's properties on postback

查看:210
本文介绍了ASP.NET MVC:更改模型的回发的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩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; }
}

和一个视图页面(Create.aspx)是这样的:

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);
}

Html.TextBox()方法总是genereates文本框的默认值,甚至回传,该对象被传递回与自己的价值观不同的属性了。现在,理所当然的,我想不出一个现实世界的例子,为什么我愿意做这样的事情,但我还是不明白,为什么我总是最后填充上分别设置了创建行动,该模型的价值观有文本框与 AcceptVerbs(HttpVerbs.Get)属性。

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.

注意:我试过 Html.TextBox(名,Model.Name)但结果还是一样。我验证了以 AcceptVerbs(HttpVerbs.Post)创建行动实际运行,经由ViewData的传递一个值到视图。
此外,显示udated值时,我的输出值与&LT;%= Model.Name%方式&gt; 但同样,不是在文本框

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?

推荐答案

如果您绑定通过方法的声明或的UpdateModel或TryUpdateModel一个对象,如TestObject中的POST请求的结果,一个名为的ModelState属性将得到使用这些值填充。该HTML助手,如文本框会一直绑定到的ModelState了一个明确的传递模型对象。

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.

这篇关于ASP.NET MVC:更改模型的回发的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆