Hi sunnyk21,
Check this example. Now please take its reference and correct your code.
Model
public class CustomerModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Salary { get; set; }
public List<SelectListItem> PsuList { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
CustomerModel model = new CustomerModel();
model.PsuList = GetPsu();
return View(model);
}
[HttpPost]
public ActionResult Index(CustomerModel cs)
{
if (!string.IsNullOrEmpty(cs.Salary))
{
string landfree = @"^[0-9]+(\.[0-9]{1,4})$";
Regex re = new Regex(landfree);
if (!re.IsMatch(cs.Salary))
{
ModelState.AddModelError("LandFreeHold", "Land Entry Not Valid");
}
}
cs.PsuList = GetPsu();
return View(cs);
}
private List<SelectListItem> GetPsu()
{
List<SelectListItem> List = new List<SelectListItem>();
List.Add(new SelectListItem { Text = "A", Value = "1" });
List.Add(new SelectListItem { Text = "B", Value = "2" });
List.Add(new SelectListItem { Text = "C", Value = "3" });
return List;
}
}
View
<html>
<head>
<title>Index</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<style type="text/css">
.field-validation-error
{
color: #e80c4d;
font-weight: bold;
}
</style>
</head>
<body>
<% using (Html.BeginForm("Index", "Home", FormMethod.Post))
{%>
Choose PSU:
<br />
<%:Html.DropDownListFor(model => model.PsuList, Model.PsuList, "-- Choose PSU --",new { @class = "form-control", required = "required" })%>
<br /><%:Html.TextBoxFor(model => model.Salary, new { @class = "form-control", required = "required" })%>
<%if (!ViewData.ModelState.IsValid)
{ %>
<span class="field-validation-error"><%:Html.ValidationMessage("LandFreeHold")%></span>
<%} %>
<br /><input type="submit" value="Submit Information" class="btn btn-primary" />
<% } %>
</body>
</html>
Screenshot
