How can I set the selected value of a Html.DropDownListFor? I've been having a look online and have seen that it can be achieved by using the fourth parameter so like the below:
如何设置Html.DropDownListFor的选定值?我在网上看了一下,发现可以通过使用第四个参数来实现,如下所示:
@Html.DropDownListFor(m => m, new SelectList(Model, "Code", "Name", 0), "Please select a country")
My select list then display like this:
我的选择列表显示如下:
<select id="ShipFromCountries" name="ShipFromCountries">
<option value="">Please select a country</option>
<option value="GB">United Kingdom</option>
<option value="US">United States</option>
...
</select>
But for some reason United Kingdom remains selected but I want "Please select a country" to be selected.
但出于某种原因,英国仍然被选中,但我想选择“请选择一个国家”。
Anyone know how I can achieve this?
有人知道我是怎么做到的吗?
EDIT
I've updated my code as there was a slight change in functionality however still seem to be encountering this problem. This is what is in my view:
我更新了我的代码,因为功能稍有变化,但似乎仍然遇到了这个问题。我的看法是:
@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
1
is the Id of the option
that I want selected, I have also tried with the text of the option
but that also does not work.
1是我想要选择的选项的Id,我也尝试了选项的文本,但这也不起作用。
Any ideas?
什么好主意吗?
11 个解决方案
#1
145
Your code has some conceptual issues:
您的代码有一些概念上的问题:
First,
首先,
@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
When using DropDownListFor, the first parameter is the property where your selected value is stored once you submit the form. So, in your case, you should have a SelectedOrderId
as part of your model or something like that, in order to use it in this way:
当使用DropDownListFor时,第一个参数是在提交表单之后存储所选值的属性。所以,在你的例子中,你应该有一个SelectedOrderId作为你的模型的一部分或者类似的东西,以便以这种方式使用它:
@Html.DropDownListFor(n => n.SelectedOrderId, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
Second,
第二,
Aside from using ViewBag, that is not wrong but there are better ways (put that information in the ViewModel instead), there is a "little bug" (or an unspected behavior) when your ViewBag property, where you are holding the SelectList, is the same name of the property where you put the selected value. To avoid this, just use another name when naming the property holding the list of items.
除了使用ViewBag之外,并没有错,但有更好的方法(把这个信息在ViewModel相反),有一个“小虫子”(或一个unspected行为)当你ViewBag属性,在哪里SelectList,属性的名称相同,你把所选的值。要避免这种情况,只需在命名包含项目列表的属性时使用另一个名称。
Some code I would use if I were you to avoid this issues and write better MVC code:
如果我是你,我会使用一些代码来避免这些问题,并编写更好的MVC代码:
Viewmodel:
视图模型:
public class MyViewModel{
public int SelectedOrderId {get; set;}
public SelectList OrderTemplates {get; set;}
// Other properties you need in your view
}
Controller:
控制器:
public ActionResult MyAction(){
var model = new MyViewModel();
model.OrderTemplates = new SelectList(db.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1);
//Other initialization code
return View(model);
}
In your View:
在你的观点:
@Html.DropDownListFor(n => n.SelectedOrderId, Model.OrderTemplates, "Please select an order template")
#2
15
For me was not working so worked this way:
因为我不是这样工作的:
Controller:
控制器:
int selectedId = 1;
ViewBag.ItemsSelect = new SelectList(db.Items), "ItemId", "ItemName",selectedId);
View:
观点:
@Html.DropDownListFor(m => m.ItemId,(SelectList)ViewBag.ItemsSelect)
JQuery:
JQuery:
$("document").ready(function () {
$('#ItemId').val('@Model.ItemId');
});
#3
5
When you pass a object like this:
当你传递一个像这样的对象:
new SelectList(Model, "Code", "Name", 0)
you are saying, the Source (Model
) and Key ("Code"
) the Text ("Name"
) and the selected value 0
. Problably you do not have a 0
value on your source for Code
property, so, the html helper will selected the first element. To to pass the real selectedValue to this control.
您说的是源(模型)和键(“代码”)文本(“名称”)和所选值0。很有问题的是,您的源代码中没有0值,因此,html助手将选择第一个元素。将真正的selectedValue传递给此控件。
#4
3
Make sure that you have trim the selected value before you assigning.
在分配之前,请确保对所选值进行了修剪。
//Model
/ /模型
public class SelectType
{
public string Text { get; set; }
public string Value { get; set; }
}
//Controller
/ /控制器
var types = new List<SelectType>();
types.Add(new SelectType() { Value = 0, Text = "Select a Type" });
types.Add(new SelectType() { Value = 1, Text = "Family Trust" });
types.Add(new SelectType() { Value = 2, Text = "Unit Trust"});
ViewBag.PartialTypes = types;
//View
/ /视图
@Html.DropDownListFor(m => m.PartialType, new SelectList(ViewBag.PartialTypes, "Value", "Text"), new { id = "Type" })
#5
2
If you know what will be in the view, you can also set the default value from Controller as well rather then set up it into the view/cshtml file. No need to set default value from HTML side.
如果您知道视图中的内容,还可以从Controller设置默认值,而不是将其设置为view/cshtml文件。不需要从HTML端设置默认值。
In the Controller file.
在控制器文件。
commission.TypeofCommission = 1;
return View(commission);
In the .cshtml file.
在.cshtml文件中。
@Html.DropDownListFor(row => row.TypeofCommission, new SelectList(Model.commissionTypeModelList, "type", "typeName"), "--Select--")
#6
0
You should forget the class
你应该忘记上课
SelectList
SelectList
Use this in your Controller:
在控制器中使用:
var customerTypes = new[]
{
new SelectListItem(){Value = "all", Text= "All"},
new SelectListItem(){Value = "business", Text= "Business"},
new SelectListItem(){Value = "private", Text= "Private"},
};
Select the value:
选择的值:
var selectedCustomerType = customerTypes.FirstOrDefault(d => d.Value == "private");
if (selectedCustomerType != null)
selectedCustomerType.Selected = true;
Add the list to the ViewData:
将列表添加到ViewData:
ViewBag.CustomerTypes = customerTypes;
Use this in your View:
在你的观点中使用这个:
@Html.DropDownList("SectionType", (SelectListItem[])ViewBag.CustomerTypes)
-
- - - - - -
More information at: http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc
更多信息:http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc
#7
0
Add the Controller Section
添加控制器部分
ViewBag.Orders= new SelectList(db.Orders, "Id", "business", paramid);
Add the Html Section
添加Html部分
@Html.DropDownList("Orders", null)
A simple method
一个简单的方法
#8
0
For me general solution :)
对于我来说通解:)
@{
var selectedCity = Model.Cities.Where(k => k.Id == Model.Addres.CityId).FirstOrDefault();
if (selectedCity != null)
{
@Html.DropDownListFor(model => model.Addres.CityId, new SelectList(Model.Cities, "Id", "Name", selectedCity.Id), new { @class = "form-control" })
}
else
{
@Html.DropDownListFor(model => model.Cities, new SelectList(Model.Cities, "Id", "Name", "1"), new { @class = "form-control" })
}
}
#9
0
Linq to Dropdown with empty item, selected item (works 100%)
(Strongly Typed,Chances for error minimum) Any model changes will be reflected in the binding
使用空项、选定项(工作100%)(强类型、错误最小化的可能性)下拉任何模型更改都将反映在绑定中
Controller
控制器
public ActionResult ManageSurveyGroup()
{
tbl_Survey sur = new tbl_Survey();
sur.Survey_Est = "3";
return View(sur);
}
View
视图
@{
//Step One : Getting all the list
var CompEstdList = (from ComType in db.tbl_CompEstdt orderby ComType.Comp_EstdYr select ComType).ToList();
//Step Two : Adding a no Value item **
CompEstdList.Insert(0, new eDurar.Models.tbl_CompEstdt { Comp_Estdid = 0, Comp_EstdYr = "--Select Company Type--" });
//Step Three : Setting selected Value if value is present
var selListEstd= CompEstdList.Select(s => new SelectListItem { Text = s.Comp_EstdYr, Value = s.Comp_Estdid.ToString() });
}
@Html.DropDownListFor(model => model.Survey_Est, selListEstd)
@Html.ValidationMessageFor(model => model.Survey_Est)
This method for binding data also possible
这种绑定数据的方法也是可能的
var selList = CompTypeList.Select(s => new SelectListItem { Text = s.CompTyp_Name, Value = s.CompTyp_Id.ToString(), Selected = s.CompTyp_Id == 3 ? true : false });
#10
0
I know this is not really an answer to the question, but I was looking for a way to initialize the DropDownList from a list on the fly in the view when I kept stumbling upon this post.
我知道这并不是问题的真正答案,但我正在寻找一种方法来初始化视图中列表中的下拉列表,当我不断地偶然发现这篇文章的时候。
My mistake was that I tried to create a SelectList from dictionary like this:
我的错误在于,我试图从字典中创建一个SelectList:
//wrong!
@Html.DropDownListFor(m => m.Locality, new SelectList(new Dictionary<string, string>() { { Model.Locality, Model.Locality_text } }, Model.Locality, ...
I then went digging in the official msdn doc, and found that DropDownListFor
doesn't necessarily require a SelectList
, but rather an IEnumerable<SelectListItem>
:
然后我在官方的msdn文档中挖掘,发现DropDownListFor不一定需要一个SelectList,而是一个IEnumerable
//right
@Html.DropDownListFor(m => m.Locality, new List<SelectListItem>() { new SelectListItem() { Value = Model.Locality, Text = Model.Locality_text, Selected = true } }, Model.Locality, new { @class = "form-control select2ddl" })
In my case I can probably also omit the Model.Locality
as selected item, since its a) the only item and b) it already says it in the SelectListItem.Selected
property.
在我的例子中,我也可以省略模型。局部性作为被选择的项,因为它是a)唯一的项和b)它已经在SelectListItem中说过了。选择属性。
Just in case you're wondering, the datasource is an AJAX page, that gets dynamically loaded using the SelectWoo/Select2 control.
如果您想知道,数据源是一个AJAX页面,它使用SelectWoo/Select2控件动态加载。
#11
0
public byte UserType
public string SelectUserType
You need to get one and set different one. Selected value can not be the same item that you are about to set.
你需要得到一个并设置另一个。所选值不能是您将要设置的同一项。
@Html.DropDownListFor(p => p.SelectUserType, new SelectList(~~UserTypeNames, "Key", "Value",UserType))
I use Enum dictionary for my list, that's why there is "key", "value" pair.
我的列表使用Enum字典,这就是为什么有“key”、“value”对。
#1
145
Your code has some conceptual issues:
您的代码有一些概念上的问题:
First,
首先,
@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
When using DropDownListFor, the first parameter is the property where your selected value is stored once you submit the form. So, in your case, you should have a SelectedOrderId
as part of your model or something like that, in order to use it in this way:
当使用DropDownListFor时,第一个参数是在提交表单之后存储所选值的属性。所以,在你的例子中,你应该有一个SelectedOrderId作为你的模型的一部分或者类似的东西,以便以这种方式使用它:
@Html.DropDownListFor(n => n.SelectedOrderId, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
Second,
第二,
Aside from using ViewBag, that is not wrong but there are better ways (put that information in the ViewModel instead), there is a "little bug" (or an unspected behavior) when your ViewBag property, where you are holding the SelectList, is the same name of the property where you put the selected value. To avoid this, just use another name when naming the property holding the list of items.
除了使用ViewBag之外,并没有错,但有更好的方法(把这个信息在ViewModel相反),有一个“小虫子”(或一个unspected行为)当你ViewBag属性,在哪里SelectList,属性的名称相同,你把所选的值。要避免这种情况,只需在命名包含项目列表的属性时使用另一个名称。
Some code I would use if I were you to avoid this issues and write better MVC code:
如果我是你,我会使用一些代码来避免这些问题,并编写更好的MVC代码:
Viewmodel:
视图模型:
public class MyViewModel{
public int SelectedOrderId {get; set;}
public SelectList OrderTemplates {get; set;}
// Other properties you need in your view
}
Controller:
控制器:
public ActionResult MyAction(){
var model = new MyViewModel();
model.OrderTemplates = new SelectList(db.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1);
//Other initialization code
return View(model);
}
In your View:
在你的观点:
@Html.DropDownListFor(n => n.SelectedOrderId, Model.OrderTemplates, "Please select an order template")
#2
15
For me was not working so worked this way:
因为我不是这样工作的:
Controller:
控制器:
int selectedId = 1;
ViewBag.ItemsSelect = new SelectList(db.Items), "ItemId", "ItemName",selectedId);
View:
观点:
@Html.DropDownListFor(m => m.ItemId,(SelectList)ViewBag.ItemsSelect)
JQuery:
JQuery:
$("document").ready(function () {
$('#ItemId').val('@Model.ItemId');
});
#3
5
When you pass a object like this:
当你传递一个像这样的对象:
new SelectList(Model, "Code", "Name", 0)
you are saying, the Source (Model
) and Key ("Code"
) the Text ("Name"
) and the selected value 0
. Problably you do not have a 0
value on your source for Code
property, so, the html helper will selected the first element. To to pass the real selectedValue to this control.
您说的是源(模型)和键(“代码”)文本(“名称”)和所选值0。很有问题的是,您的源代码中没有0值,因此,html助手将选择第一个元素。将真正的selectedValue传递给此控件。
#4
3
Make sure that you have trim the selected value before you assigning.
在分配之前,请确保对所选值进行了修剪。
//Model
/ /模型
public class SelectType
{
public string Text { get; set; }
public string Value { get; set; }
}
//Controller
/ /控制器
var types = new List<SelectType>();
types.Add(new SelectType() { Value = 0, Text = "Select a Type" });
types.Add(new SelectType() { Value = 1, Text = "Family Trust" });
types.Add(new SelectType() { Value = 2, Text = "Unit Trust"});
ViewBag.PartialTypes = types;
//View
/ /视图
@Html.DropDownListFor(m => m.PartialType, new SelectList(ViewBag.PartialTypes, "Value", "Text"), new { id = "Type" })
#5
2
If you know what will be in the view, you can also set the default value from Controller as well rather then set up it into the view/cshtml file. No need to set default value from HTML side.
如果您知道视图中的内容,还可以从Controller设置默认值,而不是将其设置为view/cshtml文件。不需要从HTML端设置默认值。
In the Controller file.
在控制器文件。
commission.TypeofCommission = 1;
return View(commission);
In the .cshtml file.
在.cshtml文件中。
@Html.DropDownListFor(row => row.TypeofCommission, new SelectList(Model.commissionTypeModelList, "type", "typeName"), "--Select--")
#6
0
You should forget the class
你应该忘记上课
SelectList
SelectList
Use this in your Controller:
在控制器中使用:
var customerTypes = new[]
{
new SelectListItem(){Value = "all", Text= "All"},
new SelectListItem(){Value = "business", Text= "Business"},
new SelectListItem(){Value = "private", Text= "Private"},
};
Select the value:
选择的值:
var selectedCustomerType = customerTypes.FirstOrDefault(d => d.Value == "private");
if (selectedCustomerType != null)
selectedCustomerType.Selected = true;
Add the list to the ViewData:
将列表添加到ViewData:
ViewBag.CustomerTypes = customerTypes;
Use this in your View:
在你的观点中使用这个:
@Html.DropDownList("SectionType", (SelectListItem[])ViewBag.CustomerTypes)
-
- - - - - -
More information at: http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc
更多信息:http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc
#7
0
Add the Controller Section
添加控制器部分
ViewBag.Orders= new SelectList(db.Orders, "Id", "business", paramid);
Add the Html Section
添加Html部分
@Html.DropDownList("Orders", null)
A simple method
一个简单的方法
#8
0
For me general solution :)
对于我来说通解:)
@{
var selectedCity = Model.Cities.Where(k => k.Id == Model.Addres.CityId).FirstOrDefault();
if (selectedCity != null)
{
@Html.DropDownListFor(model => model.Addres.CityId, new SelectList(Model.Cities, "Id", "Name", selectedCity.Id), new { @class = "form-control" })
}
else
{
@Html.DropDownListFor(model => model.Cities, new SelectList(Model.Cities, "Id", "Name", "1"), new { @class = "form-control" })
}
}
#9
0
Linq to Dropdown with empty item, selected item (works 100%)
(Strongly Typed,Chances for error minimum) Any model changes will be reflected in the binding
使用空项、选定项(工作100%)(强类型、错误最小化的可能性)下拉任何模型更改都将反映在绑定中
Controller
控制器
public ActionResult ManageSurveyGroup()
{
tbl_Survey sur = new tbl_Survey();
sur.Survey_Est = "3";
return View(sur);
}
View
视图
@{
//Step One : Getting all the list
var CompEstdList = (from ComType in db.tbl_CompEstdt orderby ComType.Comp_EstdYr select ComType).ToList();
//Step Two : Adding a no Value item **
CompEstdList.Insert(0, new eDurar.Models.tbl_CompEstdt { Comp_Estdid = 0, Comp_EstdYr = "--Select Company Type--" });
//Step Three : Setting selected Value if value is present
var selListEstd= CompEstdList.Select(s => new SelectListItem { Text = s.Comp_EstdYr, Value = s.Comp_Estdid.ToString() });
}
@Html.DropDownListFor(model => model.Survey_Est, selListEstd)
@Html.ValidationMessageFor(model => model.Survey_Est)
This method for binding data also possible
这种绑定数据的方法也是可能的
var selList = CompTypeList.Select(s => new SelectListItem { Text = s.CompTyp_Name, Value = s.CompTyp_Id.ToString(), Selected = s.CompTyp_Id == 3 ? true : false });
#10
0
I know this is not really an answer to the question, but I was looking for a way to initialize the DropDownList from a list on the fly in the view when I kept stumbling upon this post.
我知道这并不是问题的真正答案,但我正在寻找一种方法来初始化视图中列表中的下拉列表,当我不断地偶然发现这篇文章的时候。
My mistake was that I tried to create a SelectList from dictionary like this:
我的错误在于,我试图从字典中创建一个SelectList:
//wrong!
@Html.DropDownListFor(m => m.Locality, new SelectList(new Dictionary<string, string>() { { Model.Locality, Model.Locality_text } }, Model.Locality, ...
I then went digging in the official msdn doc, and found that DropDownListFor
doesn't necessarily require a SelectList
, but rather an IEnumerable<SelectListItem>
:
然后我在官方的msdn文档中挖掘,发现DropDownListFor不一定需要一个SelectList,而是一个IEnumerable
//right
@Html.DropDownListFor(m => m.Locality, new List<SelectListItem>() { new SelectListItem() { Value = Model.Locality, Text = Model.Locality_text, Selected = true } }, Model.Locality, new { @class = "form-control select2ddl" })
In my case I can probably also omit the Model.Locality
as selected item, since its a) the only item and b) it already says it in the SelectListItem.Selected
property.
在我的例子中,我也可以省略模型。局部性作为被选择的项,因为它是a)唯一的项和b)它已经在SelectListItem中说过了。选择属性。
Just in case you're wondering, the datasource is an AJAX page, that gets dynamically loaded using the SelectWoo/Select2 control.
如果您想知道,数据源是一个AJAX页面,它使用SelectWoo/Select2控件动态加载。
#11
0
public byte UserType
public string SelectUserType
You need to get one and set different one. Selected value can not be the same item that you are about to set.
你需要得到一个并设置另一个。所选值不能是您将要设置的同一项。
@Html.DropDownListFor(p => p.SelectUserType, new SelectList(~~UserTypeNames, "Key", "Value",UserType))
I use Enum dictionary for my list, that's why there is "key", "value" pair.
我的列表使用Enum字典,这就是为什么有“key”、“value”对。