C# 使用默认值从 SelectList 创建 DropDownListFor

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17215558/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:52:14  来源:igfitidea点击:

Create DropDownListFor from SelectList with default value

c#asp.net-mvc-4

提问by P.Brian.Mackey

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? E.G.

如何更新此代码以设置默认选择的选项?例如

<option value="4" selected>New</option>

<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.SelectedStatusIndexhas 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.Statusis not set by the dropdown on HTTP POST.

这将选择默认选项“新建”,但model.Item.Item.Status不是由 HTTP POST 上的下拉列表设置的。

Other Detail:

其他细节:

model.Item.Item.Statusis an int. @Model.AllStatusis a SQL table that lists all available status options.

model.Item.Item.Status是一个整数。 @Model.AllStatus是一个列出所有可用状态选项的 SQL 表。

采纳答案by thmshd

There exist already some discussions about that hereor there. One of the problems might be using a different type than stringfor the key value. I had similar problems in past and I know that i solved it like this- explicitly setting the Selectedproperty when preparing the list (in your case, AlLStatus).

已经有一些关于这里那里的讨论。问题之一可能是使用string与键值不同的类型。我曾在过去类似的问题,我知道,我解决它像这样-明确设置了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;

回答by P.Brian.Mackey

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.Statusseperately 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.SelectedStatusIndexis what is set by the dropdown. This controller implementation is what I found to be tricky.

在这种情况下model.SelectedStatusIndex是下拉菜单设置的内容。我发现这个控制器实现很棘手。

回答by Brendan Vogt

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.

你去吧。

回答by keivan kashani

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--" });

回答by Ayham D

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);