views:

82

answers:

1

I'm using MVC to create a few simple CRUD pages. I have a stringly typed user control which I include in my Create and Edit views which looks like this:

<% using (Html.BeginForm()) {%>
<div class="form">
    <%:this.Model.Title%>
    <p>
        <label for="Title">Title:</label>
        <%= Html.TextBox("Title", this.Model.Title) %>
        <%= Html.ValidationMessage("Title", "*") %>
    </p>
    <p>
        <label for="Summary">Summary:</label>
        <%= Html.TextBox("Summary", this.Model.Summary)%>
        <%= Html.ValidationMessage("Summary", "*") %>
    </p>
    <p>
        <input type="submit" value="Create" />
    </p>
</div>
<% } %>

..a Create action which looks like this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string title, string summary)
{
    Tour tour = this.TourManager.CreateTour(string.IsNullOrEmpty(title) ? DefaultText.TourTitle : title, string.IsNullOrEmpty(summary)? DefaultText.TourSummary : summary);
    return this.View("Edit", tour);
}

...and an Edit action which looks like this:

public ActionResult Edit(int id)
{
    Tour tour = this.TourManager.GetTour(id);
    return this.View("Edit", tour);
}

The problem I'm having is that <%= Html.TextBox("Title", this.Model.Title) %> is not rendering the text inside the textbox. <%:this.Model.Title%> renders it out fine so I know the model is populated. This only happens when the view is returned from the Create action (with a URL of /MyEntity/Create). When calling the Edit action with a URL looking something like /MyEntity/Edit/1, the text renders fine in the text box. Both actions pass a populated model to the edit view so I don't understand why this is happening.

+3  A: 

I want to suggest you using Post/Redirect/Get pattern. Post action should be:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string title, string summary)
{
    Tour tour = this.TourManager.CreateTour(string.IsNullOrEmpty(title) ? DefaultText.TourTitle : title, string.IsNullOrEmpty(summary)? DefaultText.TourSummary : summary);
    return RedirectToAction("Edit", new { id = tour.id } );
}

Your problem is propably connected to populated ModelState, which is not empty, because you didn't use redirection. MVC helpers use values from populated ModelState, even if you have them in specified model.

LukLed
The reason I hadn't done this was because I have a unit test which asserts that the Create action puts default values into the model. A RedirectToRouteResult does not contain the model so it makes it hard for me to test.
Charlie
That is not good reason. You should check these default values in TourManager.CreateTour tests, not this action test.
LukLed
This answer is correct. The ModelState issue is a bug. Whether it's by design or not, it bugs the heck out of me. =)
Matt Hinze