验证asp.net mvc中的下拉列表

rak*_*los 37 c# asp.net-mvc razor

//in controller
ViewBag.Categories = categoryRepository.GetAllCategories().ToList();

//in view
 @Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"))
Run Code Online (Sandbox Code Playgroud)

如何制作它以便默认情况下显示"-Select Category-"

并验证检查选择的内容(客户端和模型)

谢谢

Dar*_*rov 91

我简直无法相信有人仍然在ASP.NET MVC 3中使用ViewData/ViewBag而不是强类型视图和视图模型:

public class MyViewModel
{
    [Required]
    public string CategoryId { get; set; }

    public IEnumerable<Category> Categories { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并在您的控制器中:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Categories = Repository.GetCategories()
        }
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // there was a validation error =>
            // rebind categories and redisplay view
            model.Categories = Repository.GetCategories();
            return View(model);
        }
        // At this stage the model is OK => do something with the selected category
        return RedirectToAction("Success");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的强类型视图中:

@Html.DropDownListFor(
    x => x.CategoryId, 
    new SelectList(Model.Categories, "ID", "CategoryName"), 
    "-- Please select a category --"
)
@Html.ValidationMessageFor(x => x.CategoryId)
Run Code Online (Sandbox Code Playgroud)

此外,如果您想要客户端验证,请不要忘记引用必要的脚本:

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)

  • @wwcdwdcw,因为它们是强类型的,确保编译时安全并且重构友好. (5认同)
  • 请谨慎使用此方法:它不进行服务器端验证. (3认同)
  • @ Html.DropDownListFor(x => x.CategoryId,new SelectList(Model.Categories,"ID","CategoryName").. - 这不是强类型的. (2认同)

Jos*_*ell 8

有一个带有3个参数的重载.Html.DropdownList(name, selectList, optionLabel) 更新:下面的代码片段中有一个拼写错误.

@Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"), "-Select Category-")
Run Code Online (Sandbox Code Playgroud)

用于验证器使用

@Html.ValidationMessage("Cat")
Run Code Online (Sandbox Code Playgroud)

  • 代码段中有一个类型.它应该是`@Html.DropDownList("Cat",新的SelectList(ViewBag.Categories,"ID","CategoryName")," - 选择类别 - ") (3认同)