How do I choose which column from the “foreign” ta

2019-08-01 09:00发布

问题:

I am building a simple ASP.NET MVC app with Entity Framework Database First that allows a user to edit tables in a database. One table has a foreign key to another table. I want the user to be able to change the foreign key value.

My question: How do I choose which column from the "foreign" table is displayed to the user in the view? I scaffolded the view out, but it is displaying the wrong column.

The foreign key is in the DealerAuto table, which has columns: DealerAutoID, DealerID, DealerMakeName, DealerModelName. For some reason, the dropdown in the view for DealerAutoID is pulling in DealerMakeName. I want it to pull in DealerModelName.

View.cshtml:

@model ModelYearChange.Models.DealerAutoTrim

[...]

<div class="form-group">
        @Html.LabelFor(model => model.DealerAutoID, "DealerAutoID", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("DealerAutoID", String.Empty)
            @Html.ValidationMessageFor(model => model.DealerAutoID)
        </div>
    </div>

DealerAutoTrimController.cs:

public ActionResult Create()
    {
        ViewBag.DealerAutoID = new SelectList(db.DealerAutoes, "DealerAutoID", "DealerMakeName");
        ViewBag.DealerModelName = new SelectList(db.DealerAutoes, "DealerModelName", "DealerModelName");

        return View();
    }

    // POST: /DealerAutoTrim/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 = "DealerAutoTrimID,DealerAutoID,DealerTrimName,DealerTrimMSRP,DealerTrimMPG_City,DealerTrimMPG_Highway,DealerTrimBulletPoints,Year")] DealerAutoTrim dealerautotrim)
    {
        if (ModelState.IsValid)
        {
            db.DealerAutoTrims.Add(dealerautotrim);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.DealerAutoID = new SelectList(db.DealerAutoes, "DealerAutoID", "DealerMakeName", dealerautotrim.DealerAutoID);
        return View(dealerautotrim);
    }

回答1:

Your list binding is kind of messed up :)

Firstly, you only need one SelectList parsed to the View. So in your controller, simply have

ViewBag.DealerAutoes = SelectList(db.DealerAutoes, "DealerModelId", "DealerModelName");

Note: the second SelectList parameter specifies what field becomes the "value" of the dropdown, with the third parameter defining what field becomes the "text" value.

Then in your view, you can simply have:

@Html.DropDownListFor(m => m.DealerAutoId, (SelectList)ViewBag.DealerAutoes)