C# Mvc Id不';我不能提交
我有一个下拉列表,如下所示,试图将我的id传递给控制器,但总是显示为0C# Mvc Id不';我不能提交,c#,asp.net-mvc,razor,C#,Asp.net Mvc,Razor,我有一个下拉列表,如下所示,试图将我的id传递给控制器,但总是显示为0 <div class="form-group"> @Html.LabelFor(model => model.SagsTypersId, "SagsTypeId1", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Ht
<div class="form-group">
@Html.LabelFor(model => model.SagsTypersId, "SagsTypeId1", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("SagsTypeId1", null, htmlAttributes: new {
@class = "selectpicker",
data_show_subtext = "true",
data_live_search = "true"
})
@Html.ValidationMessageFor(model => model.SagsTypersId, "", new { @class = "text-danger" })
</div>
</div>
这是控制站
public ActionResult Create(Sag sag)
{
if (ModelState.IsValid)
{
db.Sags.Add(sag);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(sag);
}
总而言之,我的问题是Sags.SagsTypersId在尝试提交时为0。似乎找不到错误
致意
约翰尼。您没有将下拉列表附加到模型,请使用
@Html.DropDownListFor
而不是@Html.DropDownList
SagsTyperList所在的位置包含SagsTyperId和SagsTyperName
@Html.DropDownListFor(model => model.SagsTypersId,
new SelectList(SagsTypersList, "SagsTypersID", "SagsTyperName"), htmlAttributes: new {
@class = "selectpicker",
data_show_subtext = "true",
data_live_search = "true"
})
改变
@Html.DropDownList("SagsTypeId1", null, htmlAttributes: new {
@class = "selectpicker",
data_show_subtext = "true",
data_live_search = "true"
})
到
或
只需使用强类型html帮助器:
@Html.DropDownListFor(model => model.SagsTypersId,
new SelectList(SagsTypersList, "SagsTypersID", "SagsTyperName"), htmlAttributes: new {
@class = "selectpicker",
data_show_subtext = "true",
data_live_search = "true"
})
sagstyperid
不等于SagsTypeId1
!(使用强类型的DropDownListFor()
方法-@Html.DropDownListFor(m=>m.sagstyperid,(IEnumerable)@ViewBag.SagsTypeId1)
oka我会试试。然后摆脱你的ViewBag
并使用视图模型正确地完成它(请参考),谢谢我最终像这样解决了它:@Html.DropDownListFor(model=>model.sagstyperid,(IEnumerable)@ViewBag.SagsTypeId1,htmlAttributes:new{@class=“selectpicker”,data\u show\u subtext=“true”,data\u live\u search=“true”})
@Html.DropDownList("SagsTypeId", null, htmlAttributes: new {
@class = "selectpicker",
data_show_subtext = "true",
data_live_search = "true"
})
@Html.DropDownListFor(model => model.SagsTypersId,
new SelectList(SagsTypersList, "SagsTypersID", "SagsTyperName"), htmlAttributes: new {
@class = "selectpicker",
data_show_subtext = "true",
data_live_search = "true"
})