There are several approaches to accomplish this:
1. First approach: Custom validation
Model
namespace MyApplication.Models
{
public class GroupModel
{
public GroupList SelectdGroup { get; set; }
}
public enum GroupList
{
Business, Friends, Others
}
}
View
@using MyApplication.Models
@model GroupModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<b>Select Groupe: </b>
@Html.DropDownList("SelectdGroup", new SelectList(Enum.GetValues(typeof(GroupList))),"--Select Group--")
@Html.ValidationMessage("SelectedGroup")
<input type="submit" value="submit" />
}
Controller
using System.Web.Mvc;
using HtmlHelperDemo.Models;
namespace MyApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(GroupModel model)
{
var selectedValue = model.SelectdGroup;
if (selectedValue == "")
{
ModelState.AddModelError("SelectdGroup", "The Group is required");
}
return View();
}
}
}
2. Second approach: Using the attribute Required
Just add the “Required” attribute before the "SelectdGroup" field of the model and remove the check on the field "SelectdGroup" in the controller.
Model
namespace MyApplication.Models
{
public class GroupModel
{
[Required(ErrorMessage = "the Group is required.")]
public GroupList SelectdGroup { get; set; }
}
public enum GroupList
{
Business, Friends, Others
}
}
Controller
using System.Web.Mvc;
using HtmlHelperDemo.Models;
namespace MyApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(GroupModel model)
{
var selectedValue = model.SelectdGroup;
return View();
}
}
}