MVC DropDownList populate from one DB table and se

2019-05-18 20:22发布

I would like to have a dropdownlist which pulls data from a qualification table and then on HttpPost it stores the value selected in the dropdownlist to a "qualification" column on the employee table. I'm very new to MVC and I don't really know the syntax very well. I also don't know how to use jquery, vb etc. so sorry if there is a post out there that covers this and I've not seen it because I don't know what I'm looking at.

This is currently my best attempt at doing this:

Controller:

private Database1Entities db = new Database1Entities();
...
...
...
    // GET: /Home/CreateEmp
            public ActionResult CreateEmp()
            {
                ViewBag.QualList = new SelectList(db.Qualifications, "Id", "qual");
                return View();
            }
            // POST: /Home/CreateEmployee
            [HttpPost, ActionName("CreateEmployee")]
            public ActionResult CreateEmpResult(Employee emp)
            {
                if (ModelState.IsValid)
                {
                    db.Employees.Add(emp);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                ViewBag.QualList = new SelectList(db.Qualifications, "Id", "qual", emp.qualification);
                return View(emp);
            }

Create Employee View:

@model MvcDropDownList.Models.Employee
    @using (Html.BeginForm("CreateEmployee", "Home", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <table>
        <!-- other fields removed for sake of simplicity -->
        <tr>
            <td>
                @Html.Label("Select Your Qualification:")
            </td>

            <td>
                @Html.DropDownList("QualList", "--Select--")
            </td>
        </tr>
    </table>
    }

Table Structure:

Qualifications Table: Id, qual

Employee Table: Id, firstName, surName, gender, qualification

My code successfully gets the data from the "Qualification" table but doesn't post it to the "qualification" column in the "employee" table.

Any suggestions will be greatly appreciated, Thank you!

3条回答
Anthone
2楼-- · 2019-05-18 20:56

I dont know if this will help but i made a model class that creates multiple lists that i am going to use throughout my application one of the lists looks like:-

SKTDATABASEEntities db = new SKTDATABASEEntities(); public List
<Department>Departments { get { return db.Departments.ToList(); } }

my classes name is ThingLists, then from there i instantiate it in my controller class as:-

public ActionResult CreateTask() { ThingLists deps = new ThingLists(); var de = from t in deps.Departments select t.Department_Name; ViewData["depies"] = de;

and display it in my view like:-

<label for="Task">Department</label>
<div class="editor-field">
  <%: Html.DropDownList( "lsttasks", new SelectList((IEnumerable)ViewData[ "depies"], "Department"), new { id="drop1" })%>
    <br />
</div>

and that works perfectly at displaying my dropdownlist, someone suggested i use a javascript to assign selected item like:-

  < script type = "text/javascript" >
    function onSelectedIndexChanged(select) {
      var text = $("drop1").valueOf();
      document.getElementById('drop1').innerHTML = text;
    } < /script>

and at that part i still get null in my controller maybe you can get somewhere from there to. :-) i'm still waiting for a response to my question as well but if someone responds with something i will share with you.

查看更多
手持菜刀,她持情操
3楼-- · 2019-05-18 21:00

@oli_taz use my code above and viewdata instead of viewbag i just had to modify my view to

<%: Html.DropDownListFor(model=>model.Department,new SelectList((IEnumerable)ViewData["depies"], "Department")) %>

it gets values from database table "departments" and populates list created in thinglists.cs and when i save it saves exactly my selected value to my "tasks" table. I hope i explained it clear enough im kind of new.

查看更多
可以哭但决不认输i
4楼-- · 2019-05-18 21:04

You should bind your dropdownlist to the model you're returning when clicking the Save button.

In other words, this:

@Html.DropDownList("QualList", "--Select--")

Should turn into something like this:

@Html.DropDownListFor(model => model.Qualification_Id, (SelectList)ViewBag.QualList)

Edit As Stephen Muecke pointed out, you need to cast the Viewbag value to a SelectList.

Note There are multiple possibilities for DropDownListFor(). I only picked the easiest one for clarity's sake, but you could add your optional label etc.

This binds it to your model (emp):

public ActionResult CreateEmpResult(Employee emp)

Note: If your Employee class was correctly set up and has the needed Foreign keys (link to the Qualification table), there should already be a .Qualification_Id (or similar name) in your Employee class (assuming that class is your actual database entity).

These changes will cover everything you need:

  • The dropdownlist now writes the selected value into emp.Qualification_Id.
  • In your controller method, you save emp to the db.
  • EF will use the FK fields (emp.Qualification_Id) to make sure the correct values will be written in the new Employee row that will be created in the database.

As a general rule, always try to bind controls (dropdownlists, textboxes, ...) to a property of your model. if you do that, you don't need to write specific code to do basically the same.

查看更多
登录 后发表回答