【问题标题】:Drop down list with select list带有选择列表的下拉列表
【发布时间】:2019-02-15 08:46:04
【问题描述】:

这是我从模型中选择的列表。

public IEnumerable<SelectListItem> ServiceCycleList
{
    get
    {
        var Item = new List<SelectListItem>
        {
            new SelectListItem { Text = "Yearly", Value = "12" },
            new SelectListItem { Text = "Quarterly", Value = "3" },
            new SelectListItem { Text = "Monthly", Value = "1" }
        };
        return Item;
    }
}

我想为此选择列表创建一个下拉列表。我该怎么做?

【问题讨论】:

标签: c# asp.net-mvc asp.net-mvc-4


【解决方案1】:

如果它在模型视图中可用,您可以像这样创建DropDownList

@Html.DropDownListFor(model => model.YourModelProperty, new SelectList(Model.ServiceCycleList, "Value", "Text"), "Please Select...")

【讨论】:

  • 它给出了空引用异常。
  • @NiteeshJoshi 我假设空引用异常将在Model.ServiceCycleList 上。在控制器中设置,然后执行此操作
  • 我上面的代码只是基于您提供的信息的一个示例。您需要将其融入您的具体情况。我没有 100% 的信息给你一个 100% 的解决方案。
  • 我已经获取了这个服务列表类的外键。我的模型是MonthlyTransactions,在那个模型中我有ItemService的外键,它包含这个ServiceCycleList。所以,如果我像@Html.DropDownListFor(model=&gt;model.ItemServiceMasters.ServiceCycle, Model.ItemServiceMasters.ServiceCycleList, "Select Frequency", htmlAttributes: new { @class = "form-control", }) 这样写,那么它会给出空引用和System.Web.Mvc.WebViewPage&lt;TModel&gt;.Model.get returned null 的错误
【解决方案2】:

根据您上面的评论,您的操作方法正在返回一个没有模型的视图,因此您得到的错误是模型为空。

public ActionResult Index(..)
{
   .
   .

   return View(); // missing model reference
}

【讨论】:

    猜你喜欢
    • 2011-02-07
    • 2015-04-07
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多