You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MVC中使用Entity Framework数据库优先加载SQL表UID列到DropDownList

Load UID Column from 'Maquinas' Table into DropDownList with Entity Framework (Database-First)

Hey there! Let's get that UID data from your Maquinas table loaded into a DropDownList smoothly. You've already got a solid start with the backend code using Entity Framework, so let's fill in the gaps and make sure everything works end-to-end.

First, Let's Tweak the Backend (Optional but Efficient)

Your current code pulls the entire Maquinas table, but if you only need the UID column, you can optimize it by projecting just the data you need—this reduces unnecessary data transfer:

SistemaCajaConexion db = new SistemaCajaConexion();
[HttpGet]
public ActionResult Pagos() {
    // Only select the UID column instead of the full entity
    var uidList = db.Maquinas.Select(m => m.UID).ToList();
    // Create SelectList with UID as both value and display text
    ViewBag.Lista = new SelectList(uidList);
    return View();
}

If later you want to display a friendlier name alongside the UID (like a machine name), you can adjust it to:

var maquinaList = db.Maquinas.Select(m => new { m.UID, m.NombreMaquina }).ToList();
// Set UID as the value field, NombreMaquina as the display text
ViewBag.Lista = new SelectList(maquinaList, "UID", "NombreMaquina");

Now, Add the DropDownList to Your View

In your Pagos.cshtml view, add this Razor code to render the DropDownList:

<div class="form-group">
    @Html.Label("MaquinaUID", "Select a Machine UID:", new { @class = "control-label" })
    @Html.DropDownList(
        "Lista", // Matches the ViewBag property name
        null,
        "-- Choose a UID --", // Default placeholder option
        new { @class = "form-control" } // HTML attributes for styling
    )
</div>

Key Notes:

  • The first parameter of DropDownList ("Lista") must exactly match the name of the ViewBag property you set in the controller.
  • The placeholder text ("-- Choose a UID --") is optional but helps guide users—feel free to modify it to fit your language or needs.
  • If you're using a strongly-typed view model, consider switching to Html.DropDownListFor for better type safety, but the above works perfectly with ViewBag.

Once you've added the view code, run your application and you should see the DropDownList populated with all UIDs from the Maquinas table!

内容的提问来源于stack exchange,提问作者Michael Guio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:50:35