Reputation: 18977
My model:
public class ViewRequestModel
{
[Required(ErrorMessage = "some")]
[Display(Name = "some")]
public int RequestType { get; set; }
}
my controller:
[HttpPost]
[Authorize(Roles = "P")]
public PartialViewResult ViewRequests(ViewRequestModel model)
{
string vn = "";
switch (model.RequestType)
{
...
}
return PartialView(vn);
}
my view:
@{
var reqTypes = new List<ListItem> { new ListItem { Text = "t1", Value = "1" },
new ListItem { Text = "t2", Value = "2" },
new ListItem { Text = "t3", Value = "3" } };
}
@Html.DropDownListFor(model => model.RequestType, new SelectList(reqTypes), new { id = "ddlType" })
@Html.ValidationMessageFor(model => model.RequestType)
when I try to post my form, jquery validation blocks it and show the error The field RequestType must be a number
where's my mistake?
Upvotes: 2
Views: 2737
Reputation: 1039110
where's my mistake?
The fact that you are mixing some classic WebForms classes (ListItem
) with ASP.NET MVC. The consequence of this is that your <option>
elements of the dropdown do not have a value attribute. So nothing gets submitted to the form and the validation obviously fails.
Here's the correct way to populate the dropdown:
var reqTypes = new[]
{
new SelectListItem { Text = "t1", Value = "1" },
new SelectListItem { Text = "t2", Value = "2" },
new SelectListItem { Text = "t3", Value = "3" }
};
@Html.DropDownListFor(
model => model.RequestType,
reqTypes,
new { id = "ddlType" }
)
As you can see from this example I am using the SelectListItem
class which is specific for ASP.NET MVC. This generates:
<select data-val="true" data-val-number="The field some must be a number." data-val-required="some" id="ddlType" name="RequestType">
<option selected="selected" value="1">t1</option>
<option value="2">t2</option>
<option value="3">t3</option>
</select>
wheres your code generates:
<select data-val="true" data-val-number="The field some must be a number." data-val-required="some" id="ddlType" name="RequestType">
<option>t1</option>
<option>t2</option>
<option>t3</option>
</select>
The difference is obvious.
Upvotes: 4