How to return a SelectList fromatted RRS feed

  • Question

  • User539757411 posted


    I am using ASP.NET MVC, and I need to list Events with a format like:
    date - title

    How do I do this on the controller?

    Bellow is the normal code:

            public ActionResult Create()
                ViewBag.events_id = new SelectList(db.events, "id", "title");
                return View();

    Tuesday, July 30, 2019 6:16 PM

All replies

  • User475983607 posted

    The select list contains a list of options.  Each option has a value and text.  If you want to change the text then you need to create another object and populate that object with the expected format.

    Otherwise post code that reproduces the issue.  Explain the expected results and the actual results.

    Tuesday, July 30, 2019 6:35 PM
  • User1520731567 posted

    Hi xandeq,

    I am using ASP.NET MVC, and I need to list Events with a format like:
    date - title

    Do you mean you want to show date and title in dropdownlist?

    If so,you just code like:

    ViewBag.events_id = new SelectList(db.events.ToList(), "date", "title");

    You could see the format of SelectList:

    public SelectList(IEnumerable items, string dataValueField, string dataTextField);

    Just put ValueField name and TextField name on it.

    How to render in view:

    @Html.DropDownListFor(model => model.XXX, (IEnumerable<SelectListItem>)ViewBag.events_id , "---Select---", new { @class = "form-control" })

    If I mistake your mean,please post more details.

    Best Regards.

    Yuki Tao

    Wednesday, July 31, 2019 2:13 AM
  • User1429838465 posted

    I wrote a series about how to use SelectList (or dropdownlists) with ASP.NET MVC and I've touched on this topic as well.


    Hope this helps.

    Wednesday, July 31, 2019 3:37 AM
  • User-2054057000 posted

    I recommend you to go through this tutorial on that covers binding of dropdownlist in MVC in many different ways.

    Wednesday, July 31, 2019 5:31 AM