Search code examples
c#entity-frameworkmodel-view-controller

new SelectList combining two fields but getting only one


Im kinda stuck, I have a drop down that I am trying to combine two fields from the same table into. Its kinda working, here is what I get: The offending drop down list

As you can see, im pulling stuff I dont want into it, and im not pulling in my last name.

Here is my edit controller:

var DocList =
            db.Doctors
            .Select(s => new
            {
                Value = s.ID,
                FirstN = s.FirstName,
                SurN = s.Surname,

            })
            ;
ViewBag.Doctor = new SelectList(DocList, "FirstN", "SurN", episode.Doctor.ID);

and here is my razor snippet:

@Html.DropDownList("docTest")

What do you guys think is going wrong here? Thanks in advance! :)


Solution

  • In your controller you should populate your dropdown list like

    ViewBag.Doctors = new SelectList(db.Doctors.Select(d => new { d.Id, FullName = d.FirstName + " " + d.LastName }), 
                    "Id", "FullName");
    

    And then in view create dropdown with razor

    @Html.DropDownList("DoctorId", ViewBag.Doctors as SelectList, "Select doctor...", new { @class = "form-control" })
    

    Your model for form that you are creating probably should have DoctorId property which you are binding from dropdown

    @Html.DropDownListFor(m => m.DoctorId, ViewBag.Doctors as SelectList, "Select doctor...", new { @class = "form-control" })