当我在DropDownList中选择一个项目时,Selected未设置为true

时间:2018-07-23 08:58:36

标签: asp.net-mvc asp.net-mvc-4 razor

我见过this question,但不清楚以下内容:

我有一个exec sp_executesql N'SELECT [Limit2].[C1] AS [C1] FROM ( SELECT TOP (1) CASE WHEN ([Project2].[C1] IS NULL) THEN cast(0 as bigint) ELSE [Project2].[Percentage] END AS [C1] FROM ( SELECT 1 AS X ) AS [SingleRowTable1] LEFT OUTER JOIN (SELECT TOP (1) [Project1].[Percentage] AS [Percentage], cast(1 as tinyint) AS [C1] FROM ( SELECT [Extent1].[Amount] AS [Amount], [Extent1].[Percentage] AS [Percentage] FROM [dbo].[Discount] AS [Extent1] WHERE [Extent1].[Amount] <= @p__linq__0 ) AS [Project1] ORDER BY [Project1].[Amount] DESC ) AS [Project2] ON 1 = 1 ) AS [Limit2]',N'@p__linq__0 bigint',@p__linq__0=15000 ,我是这样填充的:

SelectListItem

在我看来,它是这样显示的:

MySelectList.Insert(0, new SelectListItem { Text = "Text0", Value = "0" });
MySelectList.Insert(1, new SelectListItem { Text = "Text1", Value = "1" });

如果我选择 Text0 并将模型发布到控制器,则MyId将包含所选的值,这是完美的。

但是当我浏览@Html.DropDownListFor(m => m.MyId, Model.MySelectList, new { @class = "form-control" }) 时,列表中的任何项目的MySelectList值都未设置为Selected

enter image description here

我知道我可以使用MyId查找选定的值,但是当用户从下拉菜单中选择一项并发布表格时,有什么方法可以将true设置为Selected? >

1 个答案:

答案 0 :(得分:1)

这并不意味着框架会自动对其进行更新。当您检查HTTP请求时,您会注意到只有MyId的值被传输。当通过模型绑定器重建目标视图模型时,根本不会填充MySelectList,当您在其中看到一些数据时,这可能是因为您在请求后再次填充了它。

您当然可以轻松地自己执行更新:

var selectedItem = Model.MySelectList.FirstOrDefault(x => x.Value == Model.MyId);
if (selectedItem != null)
{
    selectedItem.Selected = true;
}

问题是,它是否对您的进一步处理有所帮助。