将默认值设置为Html.DropDownListFor [英] Setting default value to Html.DropDownListFor

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

问题描述

我正在使用viewbag在mvc中填充一个下拉列表. 如果页面未与其他任何值一起保存,我想为此下拉列表设置默认值. 否则,所选项目应该是他们选择并保存页面的项目.

I am populating a dropdownlist in mvc using viewbag. i want to set a default value to this dropdownlist, if the page is not saved with any other value. Otherwise the selected item should be the one they select and save the page.

这就是我填充视图包的方式

this is how i populate my viewbag

ViewBag.ListOfCountries = new SelectList(Db.Countries, "CountryCode", "CountryName");

这是视图的一面:

<%: Html.DropDownListFor(m => m.OfficeAddressCountry, (IEnumerable<SelectListItem>)ViewBag.ListOfCountries, new{@class="required"}) %>

推荐答案

如果您要传递下拉列表的默认值,则可以传递具有默认值的默认viewmodel/model

If you want to pass default value for the dropdown list than you can do is pass default viewmodel/model with default value

示例:

public ActionResult New()
{
    MyViewModel myViewModel = new MyViewModel ();
    myViewModel.OfficeAddressCountry = default value; 
    //Pass it to the view using the `ActionResult`
    return ActionResult( myViewModel);
}

或者您可以尝试

 var list = new SelectList(Db.Countries, "CountryCode", "CountryName")
 list.Add(new SelectListItem(){Value = 1,Text = "Deafult Item",Selected = true };)
 ViewBag.ListOfCountries = list;

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

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