//in controller
ViewBag.Categories = categoryRepository.GetAllCategories().ToList();
//in view
@Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"))
我怎样才能使它默认显示“-选择类别-”
并验证以检查某些内容是否已选择(客户端和模型上)
Thanks
我简直不敢相信有人还在 ASP.NET MVC 3 中使用 ViewData/ViewBag,而不是强类型视图和视图模型:
public class MyViewModel
{
[Required]
public string CategoryId { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
在你的控制器中:
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");
}
}
然后在你的强类型视图中:
@Html.DropDownListFor(
x => x.CategoryId,
new SelectList(Model.Categories, "ID", "CategoryName"),
"-- Please select a category --"
)
@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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)