【问题标题】:ASP MVC EF6 Access foreign key table as listASP MVC EF6 访问外键表作为列表
【发布时间】:2016-10-10 10:59:55
【问题描述】:

我有 2 个表格,代码和国家,在 countries.id 上的 codes.countryid 上有一个外键约束 - 我正在使用由 Visual Studio 15 中的控制器 mvc 设置提供的基本 crud,但想替换文本通过选择 countryid 进行输入,以便用户可以从下拉列表中选择一个国家/地区,以便将 id 作为 int 输入。

如何通过提供的模型访问国家/地区列表?下面的示例剃须刀代码。我是否需要从其他模型中获取国家/地区列表?

<div class="form-group">
            <label for="CountryId" class="control-label col-md-2">Country</label>
            <select name="CountryId" class="form-control" required>
                <option value="">Please select ...</option>
 /* Model.Countries is not available even after a foreignkey constraint? */
                @foreach(var i in Model.Countries)
                {
                    <option value="@i.id">@i.Name</option>
                }
            </select>
            @Html.ValidationMessageFor(model => model.CountryId, "", new { @class = "text-danger" })
            @Html.LabelFor(model => model.CountryId, htmlAttributes: new { @class = "control-label col-md-2" })
        </div>

【问题讨论】:

    标签: asp.net-mvc entity-framework razor


    【解决方案1】:

    您应该在带有国家/地区列表的控制器操作中设置一个ViewBag 变量。

    假设您的控制器中有一个数据库上下文,您应该将以下代码放入您的操作中

    ViewBag.CountriesList = new SelectList(_context.countries.ToList(), "Id", "Name");
    

    并在您的视图中如下使用它

     @Html.DropDownListFor(a => a.countryId, (SelectList)ViewBag.CountriesList , htmlAttributes: new { @class = "form-control" })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      相关资源
      最近更新 更多