mvc5 html.editorfor,javascript - MVC5 @Html.EditorFor: Second Attribute Problem - Stack Overflow

博客作者在MVC5的创建视图中遇到一个编辑器和下拉列表的问题。用户从下拉列表选择信息后,通过JavaScript将值传递到@Html.EditorFor以保存在数据库中,但提交时该字段始终为空。问题可能在于@Html.EditorFor的第二个参数(null)。更新中提供了控制器的创建视图代码,但模型数据未能正确绑定到EditorFor字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I am having a minor frustration with the @html.EditorFor in MVC5, in a "Create View"

Basically, I have a drop down that the user selects information from. On Change, the value of the drop down is passed (via javascript) to the relative @Html.EditorFor, to be saved in the table upon submission of the view.

This is my view code for the DropDown (The dropdown itself is populated by the index controller, and works perfectly)

@Html.DropDownList("testList", null, "Select Delivery Unit", new { htmlAttributes = new { @class = "form-control" } })

This is my view code for the EditorFor:

@Html.EditorFor(model => model.DeliveryUnitID, null, "myunit", new { htmlAttributes = new { @class = "form-control" } })

Although the JavaScript is working properly, I will include that code as well, just in case it's needed:

$(function () {

$("[name='testList']").change(function () {

$("#myunit").val($(this).val());

});

});

The user selects an option from the "testlist" dropdown, and that value is passed to "myunit" with the javascript provided. That all works really well. But, when I save the data. . . that field is always empty. It's not capturing the value.

I believe the issue is with the second attribute (null).

What do I need to change to make this work properly?

Update: Here is the Create View Controller Code

public ActionResult Create()

{

List 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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值