ASP.NET MVC 3模型绑定 - ViewBag.Title冲突与ID输入="标题" [英] ASP.NET MVC 3 Model Binding - ViewBag.Title clash with input of id="Title"

查看:351
本文介绍了ASP.NET MVC 3模型绑定 - ViewBag.Title冲突与ID输入="标题"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有似乎与ViewBag动态特性的问题。可以说我有:

There seems to be an issue with the ViewBag dynamic properties. Lets say I have:

@{
    ViewBag.Title = @Model.CourseName;
}

然后在页面我有一个表格:

And then in a form on the page I have:

@Html.TextBox("Title", null, new {style="width:400px;"})

如果标题是在一个数据库表中的字段的名称。

Where Title is the name of a field in a database table.

在页面第一次打开,标题是一个id文本框取ViewBag.Title动态属性的值。

When the page first opens, text box with an id of "Title" takes the value of the ViewBag.Title dynamic property.

我对模型绑定的具体细节有点朦胧,但这似乎是一个错误,或者如果不是,它是什么,作为绑定过程的结果自然地发生,那么这将是很好的被警告了这一点。

I am a bit hazy on the exact details of Model Binding, but this does seem to be a bug, or if not, if it is something that occurs naturally as a result of the binding process, then it would be nice to be warned of this.

围绕我发现,这项工作是重命名ViewBag属性:

The work around I found, was to rename the ViewBag property to:

@{
    ViewBag.Titulo = @Model.CourseName;
}

(标题改为TITULO - 总是好知道另一种语言来避免名称冲突...)

(Title changed to Titulo - Always good to know another language to avoid name clashes...)

和问题走了。

然而,问题是:

是可以预料的这种行为?该错误很容易找到(花了一个小时的数字出来,包括写这个问题),但我怀疑其他错误可能会更多,uhmmm,深奥。

Is this behaviour to be expected? The bug was easy to find (took an hour to figure it out, including writing this question), but I suspect that other bugs might be more, uhmmm, recondite.

改写的问题:

请问模型绑定自动绑定发现在ViewBag属性?即使在强类型视图模型存在现有的财产我已经传递到页面?当然,在视图模型应该采取preference?

Does the Model Binder automatically bind properties it finds in the ViewBag? Even when an existing property exists in the strongly typed ViewModel I have passed to the page? Surely the ViewModel should take preference?

推荐答案

Html.TextBox检查的ViewData / ViewBag 值,然后再模式。为了确保它需要模式价值,你必须使用 Html.TextBoxFor

Html.TextBox checks ViewData/ViewBag values first, then Model. To make sure it takes Model value, you must use Html.TextBoxFor.

这篇关于ASP.NET MVC 3模型绑定 - ViewBag.Title冲突与ID输入="标题"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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