在 asp.net mvc 中验证下拉列表 [英] validate a dropdownlist in asp.net mvc
本文介绍了在 asp.net mvc 中验证下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
//在控制器中ViewBag.Categories = categoryRepository.GetAllCategories().ToList();//在视图中@Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"))
我怎样才能让它默认显示-选择类别-"
并验证以检查选择了某些内容(客户端和模型上)
谢谢
解决方案
我简直不敢相信还有人在 ASP.NET MVC 3 中使用 ViewData/ViewBag 而不是强类型视图和视图模型:
>
公共类 MyViewModel{[必需的]公共字符串 CategoryId { 获取;放;}公共 IEnumerable类别 { 得到;放;}}
并在您的控制器中:
公共类 HomeController:控制器{公共 ActionResult 索引(){var 模型 = 新的 MyViewModel{Categories = Repository.GetCategories()}返回视图(模型);}[HttpPost]公共 ActionResult 索引(MyViewModel 模型){如果 (!ModelState.IsValid){//有一个验证错误 =>//重新绑定类别并重新显示视图model.Categories = Repository.GetCategories();返回视图(模型);}//在这个阶段模型正常 =>对选定的类别做一些事情return RedirectToAction("成功");}}
然后在您的强类型视图中:
@Html.DropDownListFor(x =>x.CategoryId,new SelectList(Model.Categories, "ID", "CategoryName"),-- 请选择一个类别--")@Html.ValidationMessageFor(x => x.CategoryId)
此外,如果您想要客户端验证,请不要忘记引用必要的脚本:
<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>
//in controller
ViewBag.Categories = categoryRepository.GetAllCategories().ToList();
//in view
@Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"))
How can I make it so that by default it says "-Select Category-"
And validate to check something is selected (client and on the model)
Thanks
解决方案
I just can't believe that there are people still using ViewData/ViewBag in ASP.NET MVC 3 instead of having strongly typed views and view models:
public class MyViewModel
{
[Required]
public string CategoryId { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
and in your controller:
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");
}
}
and then in your strongly typed view:
@Html.DropDownListFor(
x => x.CategoryId,
new SelectList(Model.Categories, "ID", "CategoryName"),
"-- Please select a category --"
)
@Html.ValidationMessageFor(x => x.CategoryId)
Also if you want client side validation don't forget to reference the necessary scripts:
<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>
这篇关于在 asp.net mvc 中验证下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文