我尝试在SelectList中显示INV_Locations
模型中的2个字段:location_dept|location_room
或IT|Storage
。使用THIS帖子,我通过ViewData
:
INV_AssetsController - 编辑()GET :
public async Task<ActionResult> Edit(int id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
INV_Assets iNV_Assets = await db.INV_Assets.FindAsync(id);
if (iNV_Assets == null)
{
return HttpNotFound();
}
ViewBag.History = GetHistoryByAssetId(id);
ViewData["Location_Id"] = new SelectList((from l in db.INV_Locations.ToList() select new { location_room = l.location_dept + "|" + l.location_room }), "location_room", null, null);
}
INV_AssetsController - 编辑()HttpPost :
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id,Model_Id,Manufacturer_Id,Type_Id,Location_Id,Vendor_Id,Status_Id,ip_address,mac_address,note,owner,cost,po_number,description,invoice_number,serial_number,asset_tag_number,acquired_date,disposed_date,created_date,created_by,modified_date,modified_by")] INV_Assets iNV_Assets)
{
if (ModelState.IsValid)
{
iNV_Assets.modified_date = DateTime.Now;
iNV_Assets.modified_by = System.Environment.UserName;
db.Entry(iNV_Assets).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index", "Home");
}
ViewData["Location_List"] = new SelectList((from l in db.INV_Locations.ToList() select new { location_room = l.location_dept + "|" + l.location_room }), "location_room", null, null);
return View(iNV_Assets);
}
INV_Assets - 编辑()视图:
<span class="control-label col-md-2">Location:</span>
<div class="col-md-4">
@*@Html.DropDownList("Location_Id", null, htmlAttributes: new { @class = "form-control dropdown" })*@
@Html.DropDownListFor(model => model.Location_Id, (SelectList)ViewData["Location_List"], htmlAttributes: new { @class = "form-control dropdown", @id = "selectLocation" })
@Html.ValidationMessageFor(model => model.Location_Id, "", new { @class = "text-danger" })
</div>
这很接近,在我的下拉列表中呈现(例如)以下内容:
{ location_room = IT|Server }
,{ location_room = IT|Storage }
等
有没有人知道我需要做出的语法更改才能只显示选择列表中的相关部分(IT|Server
)?
答案 0 :(得分:1)
您尚未在dataTextField
构造函数中指定SelectList
属性,因此它默认为匿名对象的ToString()
方法。它必须是:(注意不需要最后一个参数)
ViewData["Location_List"] = new SelectList((from l in db.INV_Locations.ToList()
select new { location_room = l.location_dept + "|" + l.location_room }),
"location_room", "location_room");
附注:
ViewData["Location_Id"]
(我认为这是一个
错字,它应该是ViewData["Location_List"]
(根据POST
方法)Location_Id
会建议您
标识符属性(通常是int
)所以我不确定你会怎么做
期待这个工作。您正在绑定文本值“IT | Server”或
“IT |存储”到我怀疑没有的属性Location_Id
与模型或数据库字段的关系。我怀疑是什么
你真的需要这里是级联下拉列表,一个用于
部门,第二个房间(绑定到Location_Id
在选择部门时使用ajax更新。SelectList
(和其他人)
公共代码)到私有方法以避免重复代码。ViewBag
和ViewData
并删除那些可怕的
[Bind(Include = "..")]
属性答案 1 :(得分:0)
使用以下代码
var ReportingManager = _context.EmployeeDetailMaster.Select(s => new {
RecID = s.RecId,
ReportingManagerName = s.FirstName + " " + s.MiddleName + " " + s.LastName
});
ViewData.ReportingManager = new SelectList(ReportingManager, "RecId", "ReportingManagerName");