结合1的SelectList 2实体框架模型领域? [英] Combine 2 Entity Framework Model fields in 1 SelectList?

查看:129
本文介绍了结合1的SelectList 2实体框架模型领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图显示从的SelectList内我的 INV_Locations 模型2个字段: location_dept | location_room 或例如 IT |存储。使用<一个href=\"https://stackoverflow.com/questions/2758734/how-can-i-combine-two-fields-in-a-selectlist-text-description\">THIS发布我通过拼凑下面一起的ViewData

I am attempting to display 2 fields from my INV_Locations Model within a SelectList: location_dept|location_room or for example IT|Storage. Using THIS post I pieced the below together via ViewData:

INV_AssetsController - 编辑()获取

    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>

这是接近,渲染(前)在我的下拉列表如下:

This is close, rendering (ex.) the following in my dropdown:

{location_room = IT |服务器} {location_room = IT |存储}

有谁知道语法变化我需要以仅在选择列表的显示相关的部分( IT |服务器)?

Does anyone know the syntax change I need to make in order to only display the relevant part in the selectlist (IT|Server)?

推荐答案

您还没有指定在的SelectList dataTextField 属性$ C>构造函数,因此它默认为的ToString()匿名对象的方法。它需要:(请注意,不需要在最后一个参数)

You have not specified the dataTextField property in the SelectList constructor so it defaults to the ToString() method of the anonymous object. It needs to be: (note the last parameter is not required)

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

旁注:


  1. 您的GET方法具有计算机[LOCATION_ID] (我想这是一个
    错字,它应该是计算机[Location_List] (按照POST
    法)

  2. 您还没有表现出你的模型,但 LOCATION_ID 建议的
    标识属性(通常为 INT ),所以我不知道你会怎样
    预计这个工作。您具有约束力的文本值IT |服务器或
    IT |存储的财产 LOCATION_ID 我怀疑没有
    关系模型或数据库中的字段。我怀疑什么
    你真的需要这里级联下拉列表,一个用于
    部门,第二个供房(绑定到 LOCATION_ID
    这是利用最新的AJAX当选择一个部门。

  3. 我建议你重新系数生成的的SelectList (和其他
    普通code)到一个私有方法,以避免重复code。

  4. 我强烈建议你学会使用视图模型,并停止混淆
    模型 ViewBag 的ViewData ,然后取出那个可怕
    [绑定(包括=..)] 属性

  1. Your GET method has ViewData["Location_Id"] (I assume this is a typo and it should be ViewData["Location_List"] (as per the POST method)
  2. You have not shown your model but Location_Id would suggest an identifier property (usually int) so I am not sure how you would expect this to work. You are binding the text value "IT|Server" or "IT|Storage" to the property Location_Id which I suspect has no relationship to your model or the database fields. I suspect what you really need here is cascading dropdown lists, one for the department, and the second for the room (bound to Location_Id which is updated using ajax when a department is selected.
  3. I suggest you re-factor generating the SelectList (and other common code) to a private method to avoid duplicating code.
  4. I strongly recommend you learn to use view models and stop mixing up models ViewBag and ViewData and remove that dreadful [Bind(Include = "..")] attribute

这篇关于结合1的SelectList 2实体框架模型领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆