Combine 2 Entity Framework Model fields in 1 Selec

2019-09-04 06:36发布

问题:

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 - Edit() 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 - Edit() 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 - Edit() View:

        <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|Server }, { location_room = IT|Storage }, etc.

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

回答1:

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

Side notes:

  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


回答2:

use following code

    var ReportingManager = _context.EmployeeDetailMaster.Select(s => new {
                        RecID = s.RecId,
                        ReportingManagerName = s.FirstName + " " + s.MiddleName + " " + s.LastName
                    });

ViewData.ReportingManager = new SelectList(ReportingManager, "RecId", "ReportingManagerName");