2

我的模型:

public class ViewRequestModel
{
    [Required(ErrorMessage = "some")]
    [Display(Name = "some")]
    public int RequestType { get; set; }
}

我的控制器:

[HttpPost]
    [Authorize(Roles = "P")]
    public PartialViewResult ViewRequests(ViewRequestModel model)
    {
        string vn = "";
        switch (model.RequestType)
        {
            ...
        }

        return PartialView(vn);
    }

我的观点:

@{
    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)

当我尝试发布我的表单时,jquery 验证会阻止它并显示错误The field RequestType must be a number

我的错在哪里?

4

1 回答 1

4

我的错在哪里?

您将一些经典的 WebForms 类 ( ListItem) 与 ASP.NET MVC 混合在一起的事实。这样做的结果是<option>下拉列表的元素没有 value 属性。所以没有任何东西被提交给表单,验证显然失败了。

这是填充下拉列表的正确方法:

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" }
)

正如您从这个示例中看到的,我正在使用SelectListItem特定于 ASP.NET MVC 的类。这会产生:

<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>

您的代码在哪里生成:

<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>

区别很明显。

于 2013-06-01T09:06:11.640 回答