Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate a dropdownlist in asp.net mvc

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

like image 622
raklos Avatar asked Jan 18 '11 21:01

raklos


2 Answers

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> 
like image 56
Darin Dimitrov Avatar answered Oct 08 '22 23:10

Darin Dimitrov


There is an overload with 3 arguments. Html.DropdownList(name, selectList, optionLabel) Update: there was a typo in the below code snippet.

@Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"), "-Select Category-") 

For the validator use

@Html.ValidationMessage("Cat") 
like image 22
Josiah Ruddell Avatar answered Oct 08 '22 23:10

Josiah Ruddell