Question

I am attempting to create an MVC action method that allows users to progressively review a sequence of database records. Each time a user posts an update, it is submitted to the database and a new record is retrieved and rendered, for review.

However, my MVC view appears to be combining data from both the posted view model and the new view model that is created as a result of the database query. When the view simply renders property values from the view model, it correctly uses those from the view model instance that was passed to it, but when it binds an HTML form control to a view model property, it uses values from the posted view model. This means that a single view is able to display two different values for a single property on a single view model instance:

enter image description here

Here's a very simplified version of the action method ...

public ActionResult Index(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        // Write the posted model data to the repository
        // ...

        // Retrieve a new entity for the user to work on
        var alternate = new MyViewModel { Name = "New Name" };

        return View(alternate);
    }

    return View(model);
}

... and the view model ...

public class MyViewModel
{
    [Required]
    public string Name { get; set; }
}

... and the view that was used to create the above image ...

@model Mvc4TestApplication.ViewModels.MyViewModel

Name: @Model.Name
@using (Html.BeginForm())
{
    @Html.LabelFor(model => model.Name)
    @Html.TextBoxFor(model => model.Name)
    <input type="submit" value="Submit"/>
}

It seems that I have misunderstood the way MVC views discover their model data. Is there some alternate syntax that I should use to explicitly tell the view to bind its form controls to the view model that was passed to it?

Thanks,

Tim.

Was it helpful?

Solution

Try clearing the ModelState. The htmlhelpers are using the ModelState to get values.

ModelState.Clear();

Before you return View()

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