Click here to Skip to main content
14,365,158 members
Rate this:
Please Sign up or sign in to vote.
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
//Get Method
   public ActionResult Add()
        {
           //Below one line for finder
            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");
            }

            //below line for finder
            ViewBag.Name = new SelectList(db.DivisionViewModels, "ID", "Name", divisionViewModel.Name);
            PopulateDivisionDropDownList(divisionViewModel.ID);
            db.SaveChanges();            
            return View(divisionViewModel);
         }
        //below method for finder
        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);
            //db.SaveChanges();
        } 
Posted
Updated 24-Jul-16 4:57am
v2

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

use
@Html.DropDownListFor(model => model.Department)
instead of
@Html.DropDownList
Currently your dropdownlist have no 'name' attribute and no value is holding in model.Department
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100