Asp.net mvc dropdown list using ViewBag
Asked Answered
G

6

11

My table in db have fields : Id,Organisation,Info.

I want make dropdowm list like that:

<select>
  <option value='Id there'>'Organisation there'</option>...

I'm try to do it, using ViewBag:

ViewBag.Organisations = db.Organisations.ToList(); // get all fields from table using dbContext

and in View:

@Html.DropDownList('I don`t know what i shoud write here, please help')

How i can build dropdown list?

Gherardi answered 21/9, 2017 at 10:13 Comment(0)
M
16

You would need to create a SelectList in controller action using one of the constructors available and in view just pass it DropDownList method as parameter.

In Controller do this:

ViewBag.Organisations = new SelectList(db.Organisations.ToList(),"Id","Organisation");

in SelectList we need to specify which property to use as value and which to use as text in the option tag which we are specifying in last two parameters.

and then in View you would need to use it this way:

@Html.DropDownList("Organization",ViewBag.Organisations as SelectList)

Here first parameter would be used as name of select element and second one will be used to populate the option elements in the select

Following is the list of overloads available for Html.DropDownList :

https://msdn.microsoft.com/en-us/library/system.web.webpages.html.htmlhelper.dropdownlist%28v=vs.111%29.aspx?f=255&MSPPError=-2147217396

Moravia answered 21/9, 2017 at 10:22 Comment(3)
Thank you. Please tell me why i have error -There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Organization'?Gherardi
@Html.DropDownList("Organizations", ........) Change the Organization to Organizations, it needs to match the ViewBag name, which in this case is Organizations, with a plural s.Inchworm
@I.Bond are you still facing that issue ? the way i showed if you do that way i don't think you should see that errorMoravia
P
6

I recommend you to define a ViewModel for your page with a OrganisationId property. Thus this value will be filled when selecting an entry of the organisations dropdown list.

@model BCO.Models.SelectOrganisationViewModel

@{
    ViewBag.Title = "OrganisationInfo";
}

<div>
    @Html.DropDownListFor(o => o.OrganisationId,
        new SelectList(ViewBag.Organisations, "Id", "Name"))
</div>

The SelectList itself expects

  • the list to fill the DropDownList with
  • the value ("Id")
  • the text ("Name")

as parameters.

Purely answered 21/9, 2017 at 10:28 Comment(1)
While this might answer the question and help the OP, please also try to provide a little explanation and not only code.Perambulator
I
2

You can use selectlist from viewbag as follows

@Html.DropDownListFor(m => m.Name, ViewBag.GetData as SelectList, new { @class = "form-control" })

here ViewBag.GetData is populated from the controller, the controller code should be like

ViewBag.GetData = new SelectList(repository.GetOrganisation(), "ID", "OraganizationName");
Implausible answered 13/11, 2018 at 9:31 Comment(0)
P
0

controller

ViewBag.category = new SelectList(db.CategoryMasters.ToList(), "CategoryId", "CategoryName");

view

 <div class="form-group">
                @Html.LabelFor(model => model.CategoryId, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                   <div hidden>@Html.EditorFor(model => model.CategoryId, new { htmlAttributes = new { @class = "form-control", id = "categoryid" } })</div>
                        @Html.DropDownList("select", ViewBag.category as SelectList, new { @id = "category" })
                        @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
                </div>
            </div>

JS

<script type="text/javascript">
    $(document).ready(function () {
        $("#category").change(function () {
            var value = $(this).val();
            alert(+value)
            $("#categoryid").val(value);
        });
    });
</script>
Pontifical answered 7/10, 2020 at 9:17 Comment(0)
P
0

Avoid using HTML Helpers for less hassle.

Controller:

 List<SelectListItem> list = new List<SelectListItem>();
 foreach (var item in fooList)
 {
       var data = new SelectListItem()
       {
           Text = item.Text,
           Value = item.Id.ToString()
       };
       list.Add(data);
  }
  var selectList = new SelectList(list,"Value","Text");
  //The 2nd parameter specifies the selected value, 
  //The 3rd parameter specifies the text to be displayed.
  ViewBag.selectList = selectList;

Razor:

<select asp-items="ViewBag.selectList" data-placeholder="Seçiniz" data-allow-clear="true" multiple="multiple">  
</select>

Output

Present answered 6/5, 2023 at 9:11 Comment(0)
M
-2
@model CURDInMVC.Models.StudentModel


@Html.DropDownListFor(model => model.States,
                  new SelectList(ViewBag.States, "StateID", "StateName"))
Meanly answered 3/1, 2020 at 13:23 Comment(1)
Hi Ramavtar Rajput, Thank you for trying to help. However we would appreciate if you can elaborate a bit more your answer. Like explanning how it works, for instance what is doing the first line, defining the model, and so on. You can consult this StackOverflow guideline on how to write a good answer here:[stackoverflow.com/help/how-to-answer]Geld

© 2022 - 2024 — McMap. All rights reserved.