How to keep the id from the selectlist when using multiple columns in the textfield

258 views Asked by At

I am trying to show multiple columns from my database in a dropdownlist using a SelectList

public ActionResult Create()
    {
        var times = db.Show_Courses
                 .Select(x =>
                         new {
                             id = x.show_course_id,
                             times = x.show_course_before + "," + x.show_course_after
                         });


        ViewBag.course_id = new SelectList(times, "id", "times");
        return View();
    }

It shows up properly in the view but in the database the value of the id is 0

This was my code before i wanted to show two columns in the textfield of the selectlist

public ActionResult Create()
    {
        ViewBag.course_id = new SelectList(db.Show_Courses, "show_course_id", "show_course_time_before");
        return View();
    }

And here is my code in the view

        <div class="form-group">
        @Html.LabelFor(model => model.course_show_id, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("course show id", (SelectList)ViewBag.course_id, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.course_show_id, "", new { @class = "text-danger" })
        </div>
    </div>

So my question is how can I display 2 values in the Textfield of the Selectlist without the id becoming 0?

2

There are 2 answers

5
Win On

You could generate SelectList manually.

For example,

ViewBag.course_id = db.Show_Courses
   .Select(x => new SelectListItem { 
       Text = x.show_course_before + "," + x.show_course_after, 
       Value = x.show_course_id.ToString() })
   .ToList();

I personally like to use strongly type model. You can read more here

1
Ionut N On

Your code seems to be fine, you need to map the dropdown to according value from model: show_course_id - from what I see, so please update your dropdown to:

@Html.DropDownList("show_course_id", (SelectList)ViewBag.course_id, new { htmlAttributes = new { @class = "form-control" } })