In your HttpPost
controller action you must populate the AvailableForums
collection property on your view model the same way you did in your Get action that rendered the form. This is necessary if you intend to redisplay the same view containing the dropdown. This often happens in the case of a validation error. Don't forget that when you submit a form, only the selected value of the dropdown is sent to the server. The collection of all possible values is something that you need to retrieve from your backend if you intend to redisplay the same view.
DropDownListFor loses list binding in validation
-
22-09-2022 - |
Question
I am using fluentvalidation and mvc3. I have a drop down list, and it works well. I wanted to test my validation and it works EXCEPT that on validation the drop down list is empty??
What I mean is that if I purposely submit while the default SelectListItem Please Select...with a value of zero is chosen then the submit fails validation and the message shows etc. but my dropdownlist is now empty??
My controller code populating the list:
if (extforum.Count > 0)
{
foreach (var s in extforum)
model.ExternalSubscription.AvailableForums.Add(new SelectListItem(){ Text = s.ForumName, Value = s.Id.ToString() });
}
else
model.ExternalSubscription.AvailableForums.Add(new SelectListItem() { Text = "None Available", Value = "0" });
//add default value
model.ExternalSubscription.AvailableForums.Add(new SelectListItem() { Text="Please Select", Value="0", Selected=true });
My razor code:
<tr>
<td>
@Html.LabelFor(model => model.ForumName):
</td>
<td>
@Html.DropDownListFor(model => model.SelectedExtBoardId, Model.AvailableForums)
@Html.RequiredHint()
@Html.ValidationMessageFor(model => model.ExtForumBoardId)
</td>
</tr>
My validator code:
RuleFor(x => x.ExtForumBoardId)
.NotEqual(0).WithMessage("Blah"));
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow