[英]Create DropDownListFor from SelectList with default value
I have a dropdownlistfor
:我有一个dropdownlistfor
:
@Html.DropDownListFor(model => model.Item.Item.Status, new SelectList(@Model.AllStatus, "id", "Description"), new { id = "statusDropdown" })
@Html.ValidationMessageFor(model => model.Item.Item.Status)
HTML output: HTML 输出:
<select id="statusDropdown" class="valid" name="Item.Item.Status" data-val-required="The Status field is required." data-val-number="The field Status must be a number." data-val="true">
<option value="2">Completed by Admin</option>
<option value="3">General Error</option>
<option value="4">New</option>
</select>
How can I update this code to set a default selected option?如何更新此代码以设置默认选择的选项? EG例如
<option value="4" selected>New</option>
I tried:我试过了:
@Html.DropDownListFor(model => model.Item.Item.Status, new SelectList(@Model.AllStatus, "id", "Description",@Model.SelectedStatusIndex), new { id = "statusDropdown" })
@Model.SelectedStatusIndex
has a value of 4, but does not change the default option to New. @Model.SelectedStatusIndex
的值为 4,但不会将默认选项更改为 New。
I also tried:我也试过:
@Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.AllStatus, "id", "Description"), new { id = "statusDropdown" })
@Html.ValidationMessageFor(model => model.Item.Item.Status)
This selects the default option "New", but model.Item.Item.Status
is not set by the dropdown on HTTP POST.这将选择默认选项“新建”,但 HTTP POST 上的下拉列表未设置model.Item.Item.Status
。
Other Detail:其他细节:
model.Item.Item.Status
is an int. model.Item.Item.Status
是一个整数。 @Model.AllStatus
is a SQL table that lists all available status options. @Model.AllStatus
是一个 SQL 表,列出了所有可用的状态选项。
There exist already some discussions about that here or there .已经有一些关于这里或那里的讨论。 One of the problems might be using a different type than string
for the key value.问题之一可能是使用与string
不同的类型作为键值。 I had similar problems in past and I know that i solved it like this - explicitly setting the Selected
property when preparing the list (in your case, AlLStatus
).我曾在过去类似的问题,我知道,我解决它像这样-明确设置Selected
准备列表(在你的情况,当时的物业AlLStatus
)。
Would mean, for your case (in controller action):意味着,对于您的情况(在控制器操作中):
IEnumerable<SelectListItem> selectList =
from s in allStatus // where ever you get this from, database etc.
select new SelectListItem
{
Selected = (s.id == model.Item.Item.Status),
Text = cs.Description,
Value = s.id.ToString()
};
model.AllStatus = selectList;
This is in addition to the answers above.这是对上述答案的补充。 This is how I would have done it.这就是我要做的。
The view model is there to represent your data.视图模型用于表示您的数据。 So for a single drop down list I would have the following:因此,对于单个下拉列表,我将具有以下内容:
public class MyViewModel
{
public int StatusId { get; set; }
public IEnumerable<Status> Statuses { get; set; }
}
And the Status class would look like this: Status 类看起来像这样:
public class Status
{
public int Id { get; set; }
public string Description { get; set; }
}
The controller's action method to handle the view:控制器处理视图的操作方法:
public class MyController
{
private readonly IStatusService statusService;
public MyController(IStatusService statusService)
{
this.statusService = statusService;
}
public ActionResult MyActionMethod()
{
MyViewModel viewModel = new MyViewModel
{
Statuses = statusService.GetAll(),
StatusId = 4 // Set the default value
};
return View(viewModel);
}
}
The view will look like this:视图将如下所示:
@model MyProject.ViewModels.MyViewModel
@Html.DropDownListFor(
x => x.StatusId,
new SelectList(Model.Statuses, "Id", "Description", Model.StatusId),
"-- Select --"
)
@Html.ValidationMessageFor(x => x.StatusId)
There you go.你去吧。
I ended up using a variant of thomasjaworski's answer.我最终使用了 thomasjaworski 答案的变体。
View:看法:
@Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text"), new { id = "statusDropdown" })
ViewModel constructor视图模型构造函数
StatusSelectList = AllStatus.Select(x =>
new StatusSelectListItem
{
Text = x.Description,
Value = x.id.ToString()
}).ToList();
this.SelectedStatusIndex = 2;//Default Status is New
Controller on HTTP POST HTTP POST 上的控制器
I set model.Item.Item.Status
seperately from the dropdown itself:我将model.Item.Item.Status
与下拉菜单本身分开设置:
model.Item.Item.Status = model.SelectedStatusIndex;
because the dropdown set's the value of the expression passed as the first argument:因为下拉列表是作为第一个参数传递的表达式的值:
@Html.DropDownListFor(model => model.SelectedStatusIndex, new SelectList(@Model.StatusSelectList, "Value", "Text"), new { id = "statusDropdown" })
In this case model.SelectedStatusIndex
is what is set by the dropdown.在这种情况下, model.SelectedStatusIndex
是下拉列表设置的内容。 This controller implementation is what I found to be tricky.我发现这个控制器实现很棘手。
You can use "Insert" for adding default value of Dropdown and add it to your Dynamic list : By this way you don't need to use Razor in your View.您可以使用“插入”来添加 Dropdown 的默认值并将其添加到您的动态列表中:这样您就不需要在视图中使用 Razor。
List<Y> m = X.GetList();
m.Insert(0, new Y{ Name = "--Select--" });
SelectList ProductSizeList = new SelectList(_context.Sizes, "SizeId", "SizeName");
//after you create the selectList you have to create the default select list item
SelectListItem AllSize = new SelectListItem("All Size", "0");
// and after this you add this item to the begin of the selectlist
ViewData["SizeId"] = ProductSizeList.Prepend(AllSize);
I assign DropDownListFor's expression with value which is already defined in List.我为 DropDownListFor 的表达式分配了已在 List 中定义的值。 It works for me.这个对我有用。 I use List<SelectListItem> Model.IncidentPriorityList
for ddwn's selectlist.我使用List<SelectListItem> Model.IncidentPriorityList
Model.IncidentPriorityList 作为 ddwn 的选择列表。
Model.incident.INCIDENT_PRIORITY_ID = Model.DefaultParameterId; @Html.DropDownListFor(m => m.incident.INCIDENT_PRIORITY_ID, Model.IncidentPriorityList, "Select", new { @class = "form-control selectpicker", id = "drpPriority", @required = true })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.