尝试从数据库填充下拉列表时出错
本文关键字:下拉列表 出错 填充 数据库 | 更新日期: 2023-09-27 17:56:04
我正在尝试从数据库中填充DropDownListFor
项,但是当我尝试运行该程序时,它给了我错误Object reference not set to an instance
。就像方法(从数据库中获取数据并将其放入SelectList
)根本没有被调用,即使我已经从Controller
调用并设置了它。
你能告诉我出了什么问题吗?
这是我正在使用的代码:
从数据库中获取数据:(库存类)(创建数据库时,下表中的行 ID 默认存在)
private string connectionString = @"Data Source=(LocalDB)'v11.0;AttachDbFilename=|DataDirectory|'db1.mdf;Integrated Security=True";
[Display(Name = "ModuleData:")]
public string ModuleData
{
get;
set;
}
public string ID
{
get;
set;
}
public string Name
{
get;
set;
}
public IEnumerable<SelectListItem> ListData
{
get;
set;
}
public SelectList GetData()
{
List<SelectListItem> lists = new List<SelectListItem>();
using (SqlConnection conn = new SqlConnection(connectionString))
{
string query = "SELECT [Id], [Name] FROM [Query]";
conn.Open();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
ID = reader["Id"].ToString();
Name = reader["Name"].ToString();
lists.Add(new SelectListItem() { Text = Name, Value = ID });
}
}
}
conn.Close();
}
return new SelectList(lists, "Value", "Text");
}
控制器:
Inventory repository = new Inventory();
[HttpGet]
public ActionResult Module()
{
repository.ListData = repository.GetData();
return View();
}
[HttpPost]
public ActionResult Module(Inventory inven)
{
// There is a button later on and here I want to get the value of a selected `DropDownListFor`
return View(inven);
}
视图(模块):
@model Project_Name.Inventory
@{
ViewBag.Title = "Inventory";
}
<h2>Inventory</h2>
<br />
@using (Html.BeginForm())
{
<div>
<fieldset>
<legend>Inventory</legend>
<div class="editor-label">
@Html.LabelFor(u => u.ModuleData)
</div>
<div class="editor-field">
@Html.DropDownListFor(u => u.ID, Model.ListData)
</div>
</fieldset>
</div>
}
上面是我正在使用的代码,但是一旦我运行该程序,它就会给我错误,@Html.DropDownListFor(u => u.ID, Model.ListData)
说Object reference not set to an instance of an object
.
这就是我的全部问题。
谢谢
非常感谢您的回答。
在 GET 方法中,使用 分配@Html.DropDownList()
使用的SelectList
repository.ListData = repository.GetData();
但是,当您 POST 并返回视图时,您不会重新分配SelectList
,因此Model.ListData
null
。您需要在调用之前立即重复上述代码行return View(inven);
您还需要在 GET 方法中返回您的模型
repository.ListData = repository.GetData();
return View(repository); // change this
您正在调用GetData
但没有对结果执行任何操作。您需要将模型馈送到视图,否则为空:
[HttpGet]
public ActionResult Module()
{
repository.ListData = repository.GetData();
return View(repository);
}