MVC 预览版 5 - ViewData/HTML 助手怪癖

发布于 2024-07-06 01:11:59 字数 664 浏览 6 评论 0原文

以下代码位于 /Courses/Detail 操作中:

    [AcceptVerbs("GET")]
    public ActionResult Detail(int id)
    {
        ViewData["Title"] = "A View Title";
        return View(tmdc.GetCourseById(id));
    }

tmdc.GetCourseById(id) 方法返回视图的 Course 类型的实例。 视图中

<%= HTML.TextBox("Title")%>

在我用来显示 Course 对象的 Title 属性值的 。 相反,文本框显示字符串A View Title。 这是正常/预期的行为吗? 处理这个问题的最佳方法是什么?

更新
作为解决方法,我已将 ViewData["Title"] 更改为 ViewData["VIEW_TITLE"],但希望有一种更清晰的方法来处理此冲突或了解这是否是一个预期的结果。

The following code is in the /Courses/Detail action:

    [AcceptVerbs("GET")]
    public ActionResult Detail(int id)
    {
        ViewData["Title"] = "A View Title";
        return View(tmdc.GetCourseById(id));
    }

The tmdc.GetCourseById(id) method returns an instance of type Course for the View. In the View I am using

<%= HTML.TextBox("Title")%>

to display the value of the Title property for the Course object. Instead the text box is displaying the string A View Title. Is this normal/expected behavior? What would be the best way to handle this?

Update
As a workaround, I've changed ViewData["Title"] to ViewData["VIEW_TITLE"] but would like a cleaner way to handle this collision or to know if this is an expected result.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

開玄 2024-07-13 01:11:59

不幸的是,我现在不在我的开发机器上,所以我无法测试这个,但是你尝试过这样的事情吗?

<%= Html.TextBox("Title", ViewData.Model.Title) %>

Unfortunately I'm not at my dev machine right now so I can't test this, but have you tried something like this?

<%= Html.TextBox("Title", ViewData.Model.Title) %>
最初的梦 2024-07-13 01:11:59

是的,这种行为是按照设计的。 目的是您应该能够显示(在您看来)无效的用户输入,这些输入实际上永远不会被分配为模型类型实例的属性。 您可以在 此博文

您的解决方法很好,但它确实突出了视图命名空间拥挤的问题。 请记住,除了模型和 ViewData 的属性之外,其中还有 TempData、ModelState 和 HTML 内容。

如果您始终想要显示模型属性“Title”,那么您可能需要使用 HTML.TextBox 重载之一,它接受文字值而不是属性名称。

Yes, that behavior is as-designed. The intention is that you should be able to display (in your view) invalid user input which could never actually be assigned as a property of an instance of your model type. You can read more about this feature in this blog post.

Your workaround is fine, but it does highlight the issue of a congested view namespace. Keep in mind that in addition to properties of your model and ViewData, there is also TempData, ModelState, and HTML stuff in there.

If you always want to display the model property "Title," then you might want to use one of the HTML.TextBox overloads which accepts a literal value instead of a property name.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文