Reputation: 69
I've read a lot of posts on here regarding the dropdown selected value issues (not showing etc etc...) but mine is the opposite problem.
I want the drop down to always reset after the view is returned after a button submits the page through the controller action. So how I've structured it all works but is it possible to reset the dropdown list each time? I can't find a way to do it and I've tried a lot of ways, believe me.
My View:
@Model.PspSourceModel.PayAccount.PaymentProviderId
<br />
@Html.DropDownListFor(
x => x.PspSourceModel.PayAccount.PaymentProviderId,
new SelectList(Model.PspSourceModel.PaymentProviders, "Value", "Text", "-- please select --"),
"-- please select --"
My Controller:
// I've tried forcing the selected value id here - doesn't effect the dropdownlist still?
pspVM.PspSourceModel.PayAccount.PaymentProviderId = 1;
return (View(pspVM));
My Webpage shows:
1 (the id I set in the Action)
dropdownlist with the id=6 or whatever value was chosen prior to submitting the form.
From the questions and answers on SO and the wider web I thought the dropdownlist seems tied to the id you choose but how do I override that to reset the dropdown to 'please select' each time?
Thanks in advance.
Upvotes: 1
Views: 1791
Reputation: 5193
The fundamental problem here is that when MVC is rebinding the form on postback, it is not using Model but ModelState, so you can change your model as much as you like but only the bound ModelState will be used. Have you tried either of these methods on ModelState?
public bool Remove(string key);
public void SetModelValue(string key, ValueProviderResult value);
Upvotes: 4
Reputation: 1142
In your action on your postback, you could process the current value as you need to and either set the id in the model and call the view;
[HttpPost]
public ActionResult Index(ModelClass viewModel)
{
// Process Value
viewModel.PspSourceModel.PayAccount.PaymentProviderId = 6;
return View("Index", viewModel);
}
Or you could set the default values on your HttpGet, and call a RedirectToAction result in your post.
[HttpGet]
public ActionResult Index()
{
// Set the default values; the following is a rough example, and won't work.
var viewModel = new ModelClass
{
PspSourceModel.PayAccount.PaymentProviderId = 6
}
return View("Index", viewModel);
}
[HttpPost]
public ActionResult Index(ModelClass viewModel)
{
// Process Value
return RedirectToAction("Index");
}
I hope this is clear, if you need further assistance, please let me know.
Matt
Upvotes: 0