I am new to MVC and ASP.NET. My requirement is, I have to display two records in my View for the firsttime and my ViewContains one 'SWAP' button. When I press this button, post action of the controller should execute and it has to take the original viewmodel and needs to swap the two records and should render the same view. This process should carryon whenever I press Swap button.
For the first time when I am clicking SWAP, it is working fine. But when I am clicking for next time, my post controller action is taking original records and displaying the same.
My Controller Code as shown Below.
public ActionResult Dedupe()
{
var selectedClients = TempData["SelectedClients"] as DedupeClientsViewModel;
return this.View(selectedClients);
}
[HttpPost]
public ActionResult Dedupe(DedupeClientsViewModel dedupeClients)
{
if (ModelState.IsValid)
{
//my functionality
}
return this.View(dedupeClients);
}
Is there anything that I need to do with "ModelState" to get the new data from the View.
Because you are returning the same model from a post, ASP.Net MVC is assuming that you have errors that you want to present back to the user (so it retains original values). You can fix this by either clearing the model state for the entire model, or clearing the model state for one or more fields. See below. This will be done, of course, in your controller.
ModelState.Clear(); //clear entire model state
ModelState.Remove("MyObject.MyProperty"); //clear only one property
Rick Strahl has a good explanation of this issue on his blog: ASPNET-MVC-Postbacks-and-HtmlHelper-Controls-ignoring-Model-Changes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With