首页 > 解决方案 > MVC5 @Html.EditorFor:第二个属性问题

问题描述

在“创建视图”中,我对 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);
    }

标签: javascriptc#asp.netasp.net-mvc-5

解决方案


您将 HtmlFieldName 强制添加到字段编辑器这一事实会更改默认标记和发布的数据。保留字段名称,而是更新您的 jquery 以匹配模型字段名称:

$('#DeliveryUnitID').val($(this).val());

推荐阅读