How to set default value for ASP.NET MVC DropDownList from model

I am new to mvc. so I fill the dropdown menu this way

public ActionResult New()
{
    var countryQuery = (from c in db.Customers
                        orderby c.Country ascending
                        select c.Country).Distinct();
    List<SelectListItem> countryList = new List<SelectListItem>();
    string defaultCountry = "USA";
    foreach(var item in countryQuery)
    {
        countryList.Add(new SelectListItem() {
                        Text = item, 
                        Value = item, 
                        Selected=(item == defaultCountry ? true : false) });
    }
    ViewBag.Country = countryList;
    ViewBag.Country = "UK";
    return View();       
}

@Html.DropDownList("Country", ViewBag.Countries as List<SelectListItem>)

I like to know how I can populate a drop-down list from a model and also set a default value. any sample code would be a big help. thank

+4
source share
3 answers

Well, this is not the best way to do this.

Create a ViewModel that will contain everything that you want to render in the view.

public class MyViewModel{

  public List<SelectListItem> CountryList {get; set}
  public string Country {get; set}

  public MyViewModel(){
      CountryList = new List<SelectListItem>();
      Country = "USA"; //default values go here
}

Fill it with the necessary data.

public ActionResult New()
{
    var countryQuery = (from c in db.Customers
                        orderby c.Country ascending
                        select c.Country).Distinct();
    MyViewModel myViewModel = new MyViewModel ();

    foreach(var item in countryQuery)
    {
        myViewModel.CountryList.Add(new SelectListItem() {
                        Text = item, 
                        Value = item
                        });
    }
    myViewModel.Country = "UK";



    //Pass it to the view using the `ActionResult`
    return ActionResult( myViewModel);
}

In the view, declare that this view expects a model of type MyViewModel using the following line at the top of the file

@model namespace.MyViewModel 

And at any time you can use the model as you wish

@Html.DropDownList("Country", Model.CountryList, Model.Country)
+4

Html.DropDownList, , .

private string country;
public string Country
{
    get { return country ?? "UK"; }
    set { country = value; }
}

, , "" , .

+3

If it is DropDownListfilled in the controller and sent for viewing through ViewBag, you can do:

ViewBag.MyName = new SelectList(DbContextname.Tablename, "Field_ID", "Description",idtobepresented); 
0
source

Source: https://habr.com/ru/post/1535954/


All Articles