Search code examples
asp.net-mvchtml-helperviewdataasp.net-mvc-viewmodel

Confused by How ASP .NET MVC Populates Fields Based on View Model and Posted Form Values


Not sure if this question has already been asked.

I am developing an ASP .NET MVC 2 site. My view has a drop down where user can select which record to display for editing. When this drop down is changed, the field values for the currently selected record automatically get posted to the server and are saved in the session. In the response the server then returns a view for editing the newly selected record.

The problem I am having is that some of the field values from the previous record are being remembered when the new record is displayed.

In my view I have something like the following which is causing the problem:

<%= Html.TextBox("ActionTypeDetails.DisplayName", 
                 Model.ActionTypeDetails.DisplayName) %>

Here I want the posted data to populate a parameter called ActionTypeDetails which has multiple properties including DisplayName.

My controller actions looks something like this:

public ActionResult EditActionType(Guid PluginEditID, 
                                   Guid? SelectedActionTypeID, 
                                   ActionTypeViewObj ActionTypeDetails)

I have tried changing my view to this:

<%= Html.TextBox("PostedActionTypeDetails.DisplayName", 
                 Model.ActionTypeDetails.DisplayName) %>

And my controller action to this:

public ActionResult EditActionType(Guid PluginEditID, 
                                   Guid? SelectedActionTypeID, 
                                   ActionTypeViewObj PostedActionTypeDetails)

Yet it still exhibits the same problem. Can someone please explain the logic to why it works like this? What is the easiest workaround that would still allow me to use the built in model binding? I know I can clear the ModelState but this is not ideal as I want some of the other data on the form to be remembered.


Solution

  • If you post back to the same url, asp.net has mechanisms which preserve field values. More info can be found here.