DropDownList  allows user to select an item from the dropdownlist So, Today I am going to explain how to bind dropdownlist in Asp.Net MVC and How to validate dropdownlist on button click without select any value. I have taken a example to bind categories list in dropdownlist.

Create ViewModel and Entity Class

The first step is to create a ViewModel for dropdownlist . I have bound the dropdownlist in controller. In this ViewModel, I have taken Postcategories as List type and a SelectValue as int to store the selected value. The implementation is look like below. 

public class Category
{
    [Key]
    [Required(ErrorMessage="Category is required")]
     public int CategoryId { get; set; }

    [MaxLength(25)]
    public string CategoryName { get; set; }
}
public class PostViewModel
{
   public int PostId { get; set; }

   public string PostTitle { get; set; }   
  
   [Display(Name="Post Category")]        
   public List<Category> PostCategories { get; set; }

   [Required(ErrorMessage="Category is required")]
   public int SelectValue
   {
       get;
       set;            
   }
}
Create a Controller
public class PostController : BaseController
{
	public ActionResult BindCategory()
    {
       var categoryList = _categoryRepository.GetCategoryListForUser();
       var varPostViewModel = new PostViewModel();
       varPostViewModel.PostCategories = categoryList;
       varPostViewModel.SelectValue = 0;
            
         return View("BindCategory",varPostViewModel);
     }
}
Create a View
<div class="control-group">
<label class="control-label">@Html.LabelFor(m => m.PostCategories)</label>
<div class="controls">
@Html.DropDownListFor(m => m.SelectValue, new SelectList(Model.PostCategories, "CategoryId", "CategoryName"), "Please select category", new { @class = "btn-group open" })
<br />
@Html.ValidationMessageFor(m => m.SelectValue, "", new { @class = "validation_error" })
</div>
</div>

Conclusion: 

In this article I have tried to explain how to bind dropdownlist in the ASP.NET MVC framework. And How to validate a dropdownlist.

I hope this post will help you. Please put your feedback using comment which  helps me to improve myself for next post. If you have any doubts please ask your doubts or query in the comment section and if you like this post, please share it with your friends. Thanks