简体   繁体   English

使用 ASP.NET MVC 根据 ID 选择名称

[英]Select name based on ID with ASP.NET MVC

I create a new form and I want view name based on id in another table, but the id can't view in the dropdown list:我创建了一个新表单,我想要基于另一个表中的 id 的视图名称,但无法在下拉列表中查看该 id:

在此处输入图片说明

This is the view:这是视图:

<div class="form-group">
        <label class="control-label col-md-2">ID Operator</label>
        <div class="col-md-10">
            @Html.DropDownList("idOp", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.idOp, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2">Name</label>
        <div class="control-label col-md-10">
            @Html.EditorFor(model => model.tbl_operator.nama, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.tbl_operator.nama , "", new { @class = "text-danger" })
        </div>
</div> 

This is the controller :这是控制器:

public ActionResult Create()
{
    ViewBag.idEx = new SelectList(db.tbl_exercises, "idEx");
    ViewBag.idOp = new SelectList(db.tbl_operator, "idOp");
    return View();
} 

Maybe I'm missing the code.也许我错过了代码。

You need choose what field is Name , Value for SelectList like您需要选择什么字段是NameSelectList Value ,例如

ViewBag.idEx = new SelectList(tbl_exercises, "Value", "Name");

I made an example base on your code我根据你的代码做了一个例子

var tbl_exercises = new List<exercises>
{
                new exercises
                {
                    Name = "Name 1",
                    Value = 10
                },
                new exercises
                {
                    Name = "Name 2",
                    Value = 11
                }
  };

  ViewBag.idEx = new SelectList(tbl_exercises, "Value", "Name");

SelectList is defined as SelectList定义为

public SelectList(IEnumerable items, string dataValueField, string dataTextField);

In your controller, try to use在您的控制器中,尝试使用

ViewBag.idOp = new SelectList(db.tbl_operator, "idOp","idOp");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM