Asp.net mvc dropdown list using ViewBag

后端 未结 5 954
北荒
北荒 2021-01-12 03:25

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

I want make dropdowm list like that:


                        
    
提交评论

  • 2021-01-12 03:42
    @model CURDInMVC.Models.StudentModel
    
    
    @Html.DropDownListFor(model => model.States,
                      new SelectList(ViewBag.States, "StateID", "StateName"))
    
    0 讨论(0)
  • 2021-01-12 03:49

    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

    0 讨论(0)
  • 2021-01-12 03:52

    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.

    0 讨论(0)
  • 2021-01-12 04:01

    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");
    
    0 讨论(0)
  • 提交回复
    热议问题