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