Search code examples
model-view-controllerdrop-down-menuviewmodelprocedure

complete dropdownlist with stored procedure, using viewmodel


good day and thanks for your time. I have been trying to look for answers for my problem but I could not get any. I am working with mvc dropdownlists.. I have a database with a stored procedure

Select Id, Name from table

I also have a controller like this

 ` testEntities db = new testEntities();
        var result = db.read().ToList();
        return View();`

Please, help me because I would need to use a viewmodel and use that viewmodel in the view in order to get a strong typed view. Thanks a lot.


Solution

  • First, you need to define your viewmodel:

    public class TestEntityViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    Then, create this viewmodel in your controller, like this:

    testEntities db = new testEntities();
    var result = db.read().ToList();
    var viewModels = result.Select(x => new SelectListItem(){ Value = x.Id, Text = x.Name);
    return View(viewModels);
    

    At last, you can populate it in your view, like this:

    @model IEnumerable<SelectListItem>
    
    <select>
    foreach (var item on Model)
    {
        <option value="@item.Value">@item.Text</option>
    }
    </select>
    

    You can also use built-in select tag helper, or DropDownList html helper, this is the simplest example.