validate a dropdownlist in asp.net mvc

前端 未结 4 1318
遇见更好的自我
遇见更好的自我 2020-12-01 01:12
//in controller
ViewBag.Categories = categoryRepository.GetAllCategories().ToList();

//in view
 @Html.DropDownList(\"Cat\", new SelectList(ViewBag.Categories,\"ID\"         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 01:34

    Example from MVC 4 for dropdownlist validation on Submit using Dataannotation and ViewBag (less line of code)

    Models:

    namespace Project.Models
    {
        public class EmployeeReferral : Person
        {
    
            public int EmployeeReferralId { get; set; }
    
    
            //Company District
            //List                
            [Required(ErrorMessage = "Required.")]
            [Display(Name = "Employee District:")]
            public int? DistrictId { get; set; }
    
        public virtual District District { get; set; }       
    }
    
    
    namespace Project.Models
    {
        public class District
        {
            public int? DistrictId { get; set; }
    
            [Display(Name = "Employee District:")]
            public string DistrictName { get; set; }
        }
    }
    

    EmployeeReferral Controller:

    namespace Project.Controllers
    {
        public class EmployeeReferralController : Controller
        {
            private ProjDbContext db = new ProjDbContext();
    
            //
            // GET: /EmployeeReferral/
    
            public ActionResult Index()
            {
                return View();
            }
    
     public ActionResult Create()
            {
                ViewBag.Districts = db.Districts;            
                return View();
            }
    

    View:

    
                        
    @Html.LabelFor(model => model.DistrictId, "District")
    @*@Html.DropDownList("DistrictId", "----Select ---")*@ @Html.DropDownListFor(model => model.DistrictId, new SelectList(ViewBag.Districts, "DistrictId", "DistrictName"), "--- Select ---") @Html.ValidationMessageFor(model => model.DistrictId)

    Why can't we use ViewBag for populating dropdownlists that can be validated with Annotations. It is less lines of code.

提交回复
热议问题