【发布时间】:2019-01-13 10:12:36
【问题描述】:
我有一个 DropDownList,它是从一个数据库表中填充的,该表有一个名为“IncidentNumber”的列。当使用此 DropDownList 作为表单的一部分发布到不同的数据库表中时,应用程序抛出异常,因为 DropDownList 选择发布为空。在这里的任何帮助将不胜感激!
控制器动作
var items = db.ViewIncidentNumbers.ToList();
if (items != null)
{
ViewBag.data = items;
}
if (ModelState.IsValid)
{
using (LogInformationEntities4 dc = new LogInformationEntities4())
{
dc.LandLostPersonDetails.Add(land);
dc.SaveChanges();
}
}
视图中的代码
<div class="form-group">
@Html.LabelFor(model => model.Incident_Number, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("IncidentNumber", new SelectList(ViewBag.data, "IncidentNumber", "IncidentNumber"))
</div>
</div>
编辑: 事故编号类别:
public partial class IncidentNumber
{
public int Id { get; set; }
public string IncidentNumber1 { get; set; }
}
我的控制器目前看起来像:
[HttpGet]
public ActionResult NewLandMissingPerson()
{
string teamsession = string.Empty;
string username = string.Empty;
teamsession = Convert.ToString(Session["Callsign"]);
username = Convert.ToString(Session["Username"]);
LogInformationEntities4 dc = new LogInformationEntities4();
var items = dc.IncidentNumbers.ToList();
ViewBag.data = new SelectList(items.Select(x => new { Text = x.IncidentNumber1, Id = x.Id, Value = x.IncidentNumber1 }).ToList());
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult NewLandMissingPerson(LandLostPersonDetail land)
{
LogInformationEntities4 db = new LogInformationEntities4();
bool Status = false;
string response = "";
var items = db.IncidentNumbers.ToList();
ViewBag.data = new SelectList(items.Select(x => new { Text=x.IncidentNumber1, Id=x.Id, Value = x.IncidentNumber1 }).ToList());
if (ModelState.IsValid)
{
using (LogInformationEntities4 dc = new LogInformationEntities4())
{
dc.LandLostPersonDetails.Add(land);
dc.SaveChanges();
response = "New Missing Person Log Added.";
Status = true;
}
}
当前的视图如下:
@Html.DropDownListFor(model => model.Incident_Number, new SelectList(ViewBag.data, "IncidentNumber1", "IncidentNumber1"))
我目前收到一个异常,指出 System.Web.Mvc.SelectListItem 中不存在 IncidentNumber1
【问题讨论】:
-
下拉列表的渲染 HTML 是什么?它发布到的控制器操作是什么?具体而言,该操作中的哪个发布值是空的?
-
控制器动作称为 NewLandMissingPerson。发布为 null 的值是 Incident_Number 值。为下拉列表呈现的 HTML 会带来数据库中的每个值。
-
您能否发布包含属性
IncidentNumber的类,并发布您尝试提交的HttpPost控制器操作。 -
我已编辑帖子以显示此内容
-
你能发布整个控制器的操作结果吗?
标签: c# asp.net razor model-view-controller drop-down-menu