【问题标题】:How to correct bind SelectListItem with a view?如何更正将 SelectListItem 与视图绑定?
【发布时间】:2015-09-08 11:11:04
【问题描述】:

我在正确绑定 SelectListItem 和视图时遇到问题。

ItemController.cs

 public ActionResult SelectCondition()
        {

            List<SelectListItem> items = new List<SelectListItem>();

            items.Add(new SelectListItem { Text = "New", Value = "0", Selected=true });

            items.Add(new SelectListItem { Text = "Old", Value = "1" });

            var model = new Item
            {
                ItemCondition = items
            };

            return View();

        }

创建.cshtml

@Html.DropDownList("SelectCondition", (IEnumerable<SelectListItem>)Model.ItemCondition)

Item.cs

public IEnumerable<SelectListItem> ItemCondition { get; set; }

现在我有 NullReferenceException 并在 Create.cshtml

中为这一行加了下划线

【问题讨论】:

标签: c# asp.net-mvc-4 nullreferenceexception html.dropdownlistfor selectlistitem


【解决方案1】:

var model 被声明但从未使用过,这对 Visual Studio 来说不是很可疑吗?

将模型传递给视图。 return View(model).

一般建议:使用强类型视图...

【讨论】:

  • 我将模型传递给视图,但仍然有同样的问题 - NullReferenceException :(
  • Item 类中的ItemConditiion 属性设为各自的类型,然后告诉您的视图您的模型是Item 类型并删除演员表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
相关资源
最近更新 更多