asp.net-mvc MVC DropDownList SelectedValue 显示不正确
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10039006/
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
MVC DropDownList SelectedValue not displaying correctly
提问by azorr
I tried searching and didn't find anything that fixed my problem. I have a DropDownList on a Razor view that will not show the the item that I have marked as Selected in the SelectList. Here is the controller code that populates the list:
我尝试搜索并没有找到任何可以解决我的问题的东西。我在 Razor 视图上有一个 DropDownList,它不会显示我在 SelectList 中标记为 Selected 的项目。这是填充列表的控制器代码:
var statuses = new SelectList(db.OrderStatuses, "ID", "Name", order.Status.ID.ToString());
ViewBag.Statuses = statuses;
return View(vm);
Here is the View code:
这是查看代码:
<div class="display-label">
Order Status</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)
@Html.ValidationMessageFor(model => model.StatusID)
</div>
I walk through it and even in the view it has the correct SelectedValue however the DDL always shows the first item in the list regardless of the selected value. Can anyone point out what I am doing wrong to get the DDL to default to the SelectValue?
我遍历它,即使在视图中它也有正确的 SelectedValue 但是 DDL 总是显示列表中的第一项,而不管选择的值如何。谁能指出我在让 DDL 默认为 SelectValue 时做错了什么?
回答by Darin Dimitrov
The last argument of the SelectListconstructor (in which you hope to be able to pass the selected value id) is ignored because the DropDownListFor helper uses the lambda expression you passed as first argument and uses the value of the specific property.
SelectList构造函数的最后一个参数(您希望能够在其中传递选定的值 id)被忽略,因为 DropDownListFor 助手使用您作为第一个参数传递的 lambda 表达式并使用特定属性的值。
So here's the ugly way to do that:
所以这是一种丑陋的方法:
Model:
模型:
public class MyModel
{
public int StatusID { get; set; }
}
Controller:
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
ViewBag.Statuses = statuses;
var model = new MyModel();
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}
View:
看法:
@model MyModel
...
@Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)
and here's the correct way, using real view model:
这是使用真实视图模型的正确方法:
Model
模型
public class MyModel
{
public int StatusID { get; set; }
public IEnumerable<SelectListItem> Statuses { get; set; }
}
Controller:
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
var model = new MyModel();
model.Statuses = statuses;
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}
View:
看法:
@model MyModel
...
@Html.DropDownListFor(model => model.StatusID, Model.Statuses)
回答by Brendan Vogt
Create a view model for each view. Doing it this way you will only include what is needed on the screen. As I don't know where you are using this code, let us assume that you have a Create view to add a new order.
为每个视图创建一个视图模型。这样做,您将只包含屏幕上需要的内容。由于我不知道您在哪里使用此代码,让我们假设您有一个创建视图来添加新订单。
Create a new view model for your Create view:
为您的 Create 视图创建一个新的视图模型:
public class OrderCreateViewModel
{
// Include other properties if needed, these are just for demo purposes
// This is the unique identifier of your order status,
// i.e. foreign key in your order table
public int OrderStatusId { get; set; }
// This is a list of all your order statuses populated from your order status table
public IEnumerable<OrderStatus> OrderStatuses { get; set; }
}
Order status class:
订单状态类:
public class OrderStatus
{
public int Id { get; set; }
public string Name { get; set; }
}
In your Create view you would have the following:
在您的创建视图中,您将拥有以下内容:
@model MyProject.ViewModels.OrderCreateViewModel
@using (Html.BeginForm())
{
<table>
<tr>
<td><b>Order Status:</b></td>
<td>
@Html.DropDownListFor(x => x.OrderStatusId,
new SelectList(Model.OrderStatuses, "Id", "Name", Model.OrderStatusId),
"-- Select --"
)
@Html.ValidationMessageFor(x => x.OrderStatusId)
</td>
</tr>
</table>
<!-- Add other HTML controls if required and your submit button -->
}
Your Create action methods:
您的 Create 操作方法:
public ActionResult Create()
{
OrderCreateViewModel viewModel = new OrderCreateViewModel
{
// Here you do database call to populate your dropdown
OrderStatuses = orderStatusService.GetAllOrderStatuses()
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(OrderCreateViewModel viewModel)
{
// Check that viewModel is not null
if (!ModelState.IsValid)
{
viewModel.OrderStatuses = orderStatusService.GetAllOrderStatuses();
return View(viewModel);
}
// Mapping
// Insert order into database
// Return the view where you need to be
}
This will persist your selections when you click the submit button and is redirected back to the create view for error handling.
当您单击提交按钮并重定向回创建视图以进行错误处理时,这将保留您的选择。
I hope this helps.
我希望这有帮助。
回答by p.sturge
Make Sure that your return Selection Value is a String and not and int when you declare it in your model.
当您在模型中声明它时,请确保您的返回选择值是一个字符串而不是整数。
Example:
例子:
public class MyModel
{
public string StatusID { get; set; }
}
回答by JPTugirimana
For me, the issue was caused by big css padding numbers ( top & bottom padding inside the dropdown field). Basically, the item was being shown but not visible because it was way down. I FIXED it by making my padding numbers smaller.
对我来说,这个问题是由大的 css 填充数字引起的(下拉字段内的顶部和底部填充)。基本上,该项目正在显示但不可见,因为它已经下降了。我通过使我的填充数字更小来修复它。
回答by Alberto Sadoc
I leave this in case it helps someone else. I had a very similar problem and none of the answers helped.
我离开这个以防它帮助别人。我有一个非常相似的问题,但没有一个答案有帮助。
I had a property in my ViewData with the same name as the selector for the lambda expression, basically as if you would've had ViewData["StatusId"]set to something.
我的 ViewData 中有一个与 lambda 表达式的选择器同名的属性,基本上就像你已经ViewData["StatusId"]设置了一样。
After I changed the name of the anonymous property in the ViewData the DropDownList helper worked as expected.
在我更改 ViewData 中匿名属性的名称后,DropDownList 助手按预期工作。
Weird though.
虽然很奇怪。
回答by Skak2000
My solution was this... Where the current selected item is the ProjectManagerID.
我的解决方案是这样的...当前选定的项目是 ProjectManagerID。
View:
看法:
@Html.DropDownList("ProjectManagerID", Model.DropDownListProjectManager, new { @class = "form-control" })
Model:
模型:
public class ClsDropDownCollection
{
public List<SelectListItem> DropDownListProjectManager { get; set; }
public Guid ProjectManagerID { get; set; }
}
Generate dropdown:
生成下拉列表:
public List<SelectListItem> ProjectManagerDropdown()
{
List<SelectListItem> dropDown = new List<SelectListItem>();
SelectListItem listItem = new SelectListItem();
List<ClsProjectManager> tempList = bc.GetAllProductManagers();
foreach (ClsProjectManager item in tempList)
{
listItem = new SelectListItem();
listItem.Text = item.ProjectManagerName;
listItem.Value = item.ProjectManagerID.ToString();
dropDown.Add(listItem);
}
return dropDown;
}
回答by alok_dida
Please find sample code below.
请在下面找到示例代码。
public class Temp
{
public int id { get; set; }
public string valueString { get; set; }
}
Controller
控制器
public ActionResult Index()
{
// Assuming here that you have written a method which will return the list of Temp objects.
List<Temp> temps = GetList();
var tempData = new SelectList(temps, "id", "valueString",3);
ViewBag.Statuses = tempData;
return View();
}
View
看法
@Html.DropDownListFor(model => model.id, (SelectList)ViewBag.Statuses)
@Html.ValidationMessageFor(model => model.id)

