【问题标题】:enum value parameter showing up as null in controller枚举值参数在控制器中显示为 null
【发布时间】:2017-09-27 21:10:30
【问题描述】:

我正在处理一个项目,在我的索引屏幕上,我想按两个字段排序,一个是文本字段,另一个是枚举字段。我能够让文本搜索工作,但不是枚举字段。下拉框确实出现了,但传回的值始终为空。

枚举

public enum Priority 
{
    Low = 0,
    Medium = 1,
    High = 2,
    Urgent = 3,
    Compliance = 4
}

型号

[Required]
[DisplayName("Priority")]
public Priority Priority { get; set; }

[Required]
[StringLength(30, MinimumLength = 1)]
[DisplayName("Requested By")]
public string RequestedBy { get; set; }

控制器:

public ActionResult Index(string enumPriority, string searchString)
{
    var PriorityLst = new List<string>();
    var PriorityQry = from d in db.Reports
                      orderby d.Priority.ToString()
                      select d.Priority.ToString();

    PriorityLst.AddRange(PriorityQry.Distinct());
    ViewBag.Priority = new SelectList(PriorityLst);

    var reports = from m in db.Reports
                  select m;

    if (!String.IsNullOrEmpty(searchString))
    {
        reports =             reports.Where(s=>s.RequestedBy.Contains(searchString));
    }
    if (!String.IsNullOrEmpty(enumPriority))
    {
        reports = reports.Where(x => x.Priority.ToString() ==             enumPriority.ToString());
    }

查看(索引):

<p>

@Html.ActionLink("Create New", "Create")

@using (Html.BeginForm("Index", "Reports", FormMethod.Get)) 
{
<p> Priority: @Html.DropDownList("Priority", "Select")
    Requested By: @Html.TextBox("SearchString") 

    <input type="submit" value="Filter" />
</p>

【问题讨论】:

  • 包含这两个属性的模型类的名称是什么?为什么不让模型绑定器完成这项工作?
  • 您是否尝试过更改您的 Index 方法以获取 Report 类型的对象?模型绑定器应该能够为您绑定这些属性:public ActionResult Index(Report report).
  • 您也需要添加搜索字符串参数。考虑使其成为模型的属性,以便它也自动绑定。
  • 将参数名称从 enumPriority 更改为 priority
  • 好的,我采取了简单的方法并让它工作。谢谢!我确实尝试传递该对象,但它没有显示我的完整数据库。

标签: c# asp.net-mvc


【解决方案1】:

更改方法签名:

public ActionResult Index(string enumPriority, string searchString)

到:

public ActionResult Index(string priority, string searchString)

也就是说,正如 Juan 在 cmets 中指出的那样,模型绑定器可以为您完成工作。它看起来像这样:

public ActionResult Index(MyModel model)

您需要确保它包含您需要的所有属性(优先级、搜索字符串)。该模型还需要一个默认构造函数来允许模型绑定器创建对象。在这个小例子中,额外的工作似乎不值得,但在未来,更复杂的模型,或者只是具有更多属性的模型,你会很高兴将工作交给模型绑定器.

【讨论】:

    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 2015-02-12
    • 2013-11-10
    • 2017-07-04
    • 1970-01-01
    • 2022-07-11
    • 2012-03-27
    • 1970-01-01
    相关资源
    最近更新 更多