【发布时间】:2019-07-14 14:47:24
【问题描述】:
在“创建视图”中,我对 MVC5 中的 @html.EditorFor 有点失望
基本上,我有一个下拉菜单供用户从中选择信息。在更改时,下拉列表的值(通过 javascript)传递给相关的 @Html.EditorFor,以便在提交视图时保存在表中。
这是我的 DropDown 视图代码(下拉列表本身由索引控制器填充,并且运行良好)
@Html.DropDownList("testList", null, "Select Delivery Unit", new { htmlAttributes = new { @class = "form-control" } })
这是我的 EditorFor 视图代码:
@Html.EditorFor(model => model.DeliveryUnitID, null, "myunit", new { htmlAttributes = new { @class = "form-control" } })
虽然 JavaScript 工作正常,但我也会包含该代码,以防万一:
<script type="text/javascript">
$(function () {
$("[name='testList']").change(function () {
$("#myunit").val($(this).val());
});
});
</script>
用户从“testlist”下拉列表中选择一个选项,然后将该值通过提供的 javascript 传递给“myunit”。这一切都很好。但是,当我保存数据时。 . .该字段始终为空。它没有捕获价值。
我认为问题出在第二个属性(null)上。
我需要进行哪些更改才能使其正常工作?
更新:这里是创建视图控制器代码
public ActionResult Create()
{
List<SelectListItem> testList = db.ICS_Units.Select(x => new SelectListItem { Value = x.DeliveryUnitID.ToString(), Text = x.DeliveryUnit, Selected = false }).DistinctBy(p => p.Text).ToList();
ViewBag.testList = new SelectList(testList, "Value", "Text");
return View();
}
// POST: InternalOrders/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "TransID,SuppliesID,OriginalDate,TransType,LastUpdatedBy,Contact,OpenClosed,CurrentStatus,CurrentStatusDate,RequsitionNumber,PONumber,DeliveryMonth,DeliveryYear,UnitsOrdered,Emergency,Comments,DeliveryUnitID")] ICS_Transactions iCS_Transactions)
{
if (ModelState.IsValid)
{
db.ICS_Transactions.Add(iCS_Transactions);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(iCS_Transactions);
}
【问题讨论】:
-
您正在强制使用“myunit”的字段名称。当您“保存数据”时,您是否使用包含属性名称“myunit”的模型发布到控制器操作?
-
请添加保存数据的控制器代码。
-
@jcruz:我的概念是“myunit”是 id?以便 javascript 知道在哪里可以找到放置值的位置?是的,发布到控制器操作,但模型没有“myunit”的属性名称。 Myunit 应该只是一个 ID。我来自旧的 asp.net 网络表单世界。文本框可以被赋予一个 ID,并且您可以将变量传递给它。这就是我在这里想要完成的。
-
@亚历山大。我现在将添加控制器代码。
标签: javascript c# asp.net asp.net-mvc-5