繁体   English   中英

asp.net mvc 5 DropDownList nullable int默认选项不为null

[英]asp.net mvc 5 DropDownList nullable int default option not null

我有一个关于mvc DropDownList的问题,关于它的很多主题,但没有一个有相同的问题。

我想为我的DropDownList选择默认选项,但我还需要“全部”选项的附加选项。

所以我的控制器将默认值2绑定到下拉列表

 public ActionResult Index(int? All = 2){ ...

在cshtml我有

 @Html.DropDownList("All","All items")

所有列表都是这样填写的

 ViewData["All"] = new SelectList(CommonLists.property_types.Select(x => new { v = x.Value, t = x.Key.ToLower() }), "v", "t", All);

property_types

  public static Dictionary<string, int> property_types = new Dictionary<string, int>() { 
    { "House", 1 }, { "Flat", 2 }, { "Garden", 3 }

所以它应该像这样工作

  • 当第一次输入默认选择值是2,等于“平”时,只显示“平”项(工作)
  • 用户可以从列表中将其更改为其他选项(工作)
  • 用户可以更改为一次查看所有项目,无论选择“所有项目”的类别(这不起作用)

我认为它应该工作,但令我惊讶的是,当我选择“所有项目”时,mvc不返回null它只返回默认的int值2 ,所以基本上没有办法查询所有项目。

这假设是这样的吗? 自动生成的“所有项目”是空值,所以我假设mvc会将其转换为null,但事实并非如此。

如何解决这个问题?

这个问题是不是null不被POST返回,但null由POST返回。

由于您的操作的默认值为2 当动作接收为null ,它正在使用默认值初始化变量,在这种情况下为2

public ActionResult Index(int? All = 2)

您想要做什么来区分“所有项目”和应用程序的默认行为。 在这种情况下,默认行为是仅显示平面

您可以通过在控制器内部构建“所有项目”来实现该目标。

public ActionResult Index(int? All = 2)
{
    var propertyTypesSelectList = new SelectList(property_types.Select(x => new {v = x.Value, t = x.Key.ToLower()}), "v", "t", All).ToList();
    propertyTypesSelectList.Insert(0, new SelectListItem() { Value = "0", Text = "All items"});

    ViewData["All"] = propertyTypesSelectList;
    return View();
}

并将您的视图更改为此

@Html.DropDownList("All") 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM