I ran into an issue with the default value of a <select>
element not being properly set to the value of the property model I set it to in the tag helper.
My original code that led to the issue:
Controller Action:
public async Task<ActionResult> Test(int? id = null, string siteAbbreviation = null)
{
MyModel model = await GetModelData(id, siteAbbreviation);
model.SiteAbbreviation = "AA";
return PartialView("Test", model);
}
View:
@model MyModel
<select asp-for="SiteAbbreviation" class="form-control">
<option>-select-</option>
<option value="AA">Some AA Text</option>
<option value="BB">Some BB Text</option>
<option value="CC">Some CC Text</option>
</select>
// Note that I also tried with @DropDownListFor(m => m.SiteAbbreviation)
In the above controller action, I'm overwriting the model property SiteAbbreviation to be "AA" - so this should always be the selected option; however, when calling the action like so: Test?id=0&siteAbbreviation=BB, "BB" becomes the selected option. Using breakpoints, I can see that Model.SiteAbbreviation is properly being overwritten when it gets to the view.
I managed to fix this by changing the controller action's argument name from string siteAbbreviation
to string site
. This implies that the argument being the same as my model property threw the selected value of my tag helper off.
Why is that?
When binding data in client side,it will get value from ModelState prior to Model .You can try to add ModelState.Clear
into the action:
public async Task<ActionResult> Test(int? id = null, string siteAbbreviation = null)
{
MyModel model = await GetModelData(id, siteAbbreviation);
ModelState.Clear();
model.SiteAbbreviation = "AA";
return PartialView("Test", model);
}