如何设置MVC 4剃刀默认值DropDownListFor [英] How to set Default value in MVC 4 razor DropDownListFor

查看:212
本文介绍了如何设置MVC 4剃刀默认值DropDownListFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有MVC的Razor视图与很多DropDrownFor的。
我想默认值设置为DropdownListFor。

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

这是我的看法:

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

这是我的ViewBag:

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

推荐答案

你需要做的是这样的:

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

有关在国家列表示例,你有一个项目国家或地区名称和它的ID为1,则需要通过1最后一个参数,并显示与该ID为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.

示例:

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"});

现在在控制器动作:

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

现在在的Test2 将显示选定的默认视图中。

Now the Test2 will be shown selected default in View.

这篇关于如何设置MVC 4剃刀默认值DropDownListFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆