How to set Default value in MVC 4 razor DropDownLi

2019-01-29 03:35发布

问题:

I Have MVC Razor view with lot of DropDrownFor. i wanna set default value to that DropdownListFor.

This is my View:

@Html.DropDownListFor(model => model.DestCountryId, ViewBag.CountryIdList as SelectList, "select", new { @class = "form-control input-sm" })

This is my ViewBag:

 ViewBag.CountryIdList = new SelectList(db.Countries.Where(a => a.Currency != null), "Id", "Name");

Ho w to set Default value in this scenario

回答1:

you need to do like this:

ViewBag.CountryIdList = new SelectList(db.Countries.Where(a => a.Currency != null), "Id", "Name",1);

For Example in the Countries List, you have a item CountryName and its id is 1, you need to pass the 1 in the last parameter, and element with that Id 1 will be shown selected by default.

Example:

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

List<Country> list = new List<Country>();

list.Add(new Country{ Id = 1, Name="Test"});
list.Add(new Country{ Id = 2, Name="Test2"});

now in controller action:

int Selected = 2;
ViewBag.CountryIdList = new SelectList(list, "Id", "Name",Selected);

Now the Test2 will be shown selected default in View.



回答2:

The first parameter that you give to @Html.DropDownListFor is an expression that identifies the object that contains the properties to display.

You have already given "Selected" as default value if nothing is selected or your DestCountryId doesn't hold any value or it doesn't matches with the values passed in the CountryIdList. You need to assign a value to DestCountryId before rendering this view. You can do this either in controller or where you build your view-model like:

viewModel.DestCountryId = 33; where this value exists in the selectList value that you are giving to dropdownlist.

Also, a good practise is to not to use ViewBag. Try creating a simple model with properties that your current view needs.

You can also use SelectList(IEnumerable, String, String, Object) overload of SelectList where the object is the selected value.

Hope this helps.