Click here to Skip to main content
15,892,480 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
HTML
<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
C#
//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 3:57am
v2

1 solution

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
 
Share this answer
 

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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900