Question

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.

Was it helpful?

Solution

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) %>

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top