Hi,
I am new for mvc5, I have created 2 master pages and drop down list for selector, when I selecting value from drop down that value is not saving in Db. please help me. that particular field is showing error message: "Department field is required". I guess that field value is not taking after selecting value from same field drop down list. Pleas help me where I did mistake in this.
below is my code.
Thank you.
What I have tried:
View Page
<div class="form-group">
@Html.LabelFor(model => model.Department, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-6" style="width:275px;">
@Html.DropDownList("ID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Department, "", new { @class = "text-danger" })
</div>
</div>
below code for Controller
public ActionResult Add()
{
PopulateDivisionDropDownList();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add([Bind(Include = "ID,Code,Name,Department,CreatedDateandTime")] DivisionViewModel divisionViewModel)
{
if (ModelState.IsValid)
{
db.DivisionViewModels.Add(divisionViewModel);
db.SaveChanges();
return RedirectToAction("List");
}
ViewBag.Name = new SelectList(db.DivisionViewModels, "ID", "Name", divisionViewModel.Name);
PopulateDivisionDropDownList(divisionViewModel.ID);
db.SaveChanges();
return View(divisionViewModel);
}
private void PopulateDivisionDropDownList(object selectedDepartment = null)
{
var departmentquery = from dept in db.DepartmentViewModels
orderby dept.Name
select dept;
db.SaveChanges();
ViewBag.ID = new SelectList(departmentquery, "ID", "Name", selectedDepartment);
}