asp.net-mvc Html.DropdownListFor 未设置选定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19476530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Html.DropdownListFor selected value not being set
提问by Ibrar Hussain
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")
1is the Id of the optionthat I want selected, I have also tried with the text of the optionbut that also does not work.
1是option我想要选择的 Id ,我也尝试过使用 的文本,option但这也不起作用。
Any ideas?
有任何想法吗?
回答by Romias
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 SelectedOrderIdas part of your model or something like that, in order to use it in this way:
使用 DropDownListFor 时,第一个参数是提交表单后存储所选值的属性。因此,在您的情况下,您应该将 aSelectedOrderId作为模型的一部分或类似的东西,以便以这种方式使用它:
@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 putthe selected value. To avoid this, just use another name when naming the property holding the list of items.
除了使用 ViewBag 之外,这并没有错,但有更好的方法(将这些信息放在 ViewModel 中),当您持有 SelectList 的 ViewBag 属性是与您放置所选值的属性相同的名称。为避免这种情况,只需在命名包含项目列表的属性时使用另一个名称。
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")
回答by VINICIUS SIN
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:
查询:
$("document").ready(function () {
$('#ItemId').val('@Model.ItemId');
});
回答by Felipe Oriani
When you pass an 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. You probably do not have a 0value in your source for Codeproperty, so the HTML Helper will select the first element to pass the real selectedValue to this control.
您是说: Source ( Model) 和 Key ( "Code") Text ( "Name") 和所选值0。您的属性0源中可能没有值Code,因此 HTML 帮助程序将选择第一个元素以将真正的 selectedValue 传递给此控件。
回答by Nalan Madheswaran
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" })
回答by Smit Patel
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--")
回答by g.breeze
You should forget the class
你应该忘记上课
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
回答by g.breeze
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
Linq to Dropdown with empty item, selected item (works 100%)
(Strongly Typed,Chances for error minimum) 任何模型变化都将反映在绑定中
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 });
回答by Damian Vogel
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.
我知道这并不是问题的真正答案,但是当我不断地发现这篇文章时,我一直在寻找一种方法来从视图中的动态列表中初始化 DropDownList。
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 DropDownListFordoesn't necessarily require a SelectList, but rather an IEnumerable<SelectListItem>:
然后我去挖掘官方的msdn doc,发现DropDownListFor不一定需要一个SelectList,而是一个IEnumerable<SelectListItem>:
//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.Localityas selected item, since its a) the only item and b) it already says it in the SelectListItem.Selectedproperty.
在我的情况下,我可能也可以省略Model.Locality作为选定的项目,因为它 a) 唯一的项目和 b) 它已经在SelectListItem.Selected属性中说出来了。
Just in case you're wondering, the datasource is an AJAX page, that gets dynamically loaded using the SelectWoo/Select2 control.
以防万一,数据源是一个 AJAX 页面,它使用 SelectWoo/Select2 控件动态加载。
回答by MEO
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 字典作为我的列表,这就是为什么有“键”,“值”对。
回答by Arun Prasad E S
I had a similar issue, I was using the ViewBag and Element name as same. (Typing mistake)
我有一个类似的问题,我使用相同的 ViewBag 和 Element 名称。(打字错误)

