views:

569

answers:

2

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.

Better Way of Handling This
Thanks for your help Kevin. I used your answer as a guide and it worked: <%= Html.TextBox("Title", ((Courses.Course)ViewData.Model).Title)%>

This is much less ambiguous than the first method I was using!

+1  A: 

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) %>
Kevin Pang
+1  A: 

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.

Craig Stuntz
Thanks for the help Craig...I forgot about the possible conflicts with TempData and the others.
mwilkes