【问题标题】:Scaffolding MVC Controller - how to indicate dataValueField and dataTextField?脚手架 MVC 控制器 - 如何指示 dataValueField 和 dataTextField?
【发布时间】:2021-02-09 19:45:01
【问题描述】:

SelectList 的重载方法之一(来自 Microsoft.AspNetCore.Mvc.Rendering 命名空间)定义为:

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

当我搭建一个“带有视图的 MVC 控制器,使用实体框架”并创建我的 CRUD 页面时,我可能会在我的控制器中看到以下方法:

public IActionResult Create()
        {
            ViewData["Continent"] = new SelectList(_context.Continent, **"ContinentID", "ContinentID"**);
            ViewData["Country"] = new SelectList(_context.Country, **"CountryID", "CountryName"**);
            return View();
        }

提供给 dataTextField 参数的字段在大陆/国家之间是不同的。 MVC/EntityFramework 在搭建 Controller 时如何决定向 dataTextField 提供哪个字段?个别模型或 DbContext 中是否有我忽略的东西?我希望 Continent 的 dataTextField 为“ContinentName”,这样以后我需要删除然后重新搭建 Controller 时就不必手动更改它。


编辑:

以下是模型定义:

我上面贴的控制器的模型:

using System;
using System.Collections.Generic;

namespace Project.Models
{
    public partial class ProjectForm
    {
        public int ProjectFormID { get; set; }
        public int ContinentID { get; set; }
        public int CountryID { get; set; }

        public virtual Continent ContinentNavigation { get; set; }
        public virtual Country CountryNavigation { get; set; }
    }
}

以我希望看到的方式在 dataTextField 中显示“CountryName”:

namespace Project.Models
{
    public partial class Country
    {
        public int CountryID { get; set; }
        public string CountryName { get; set; }

        public virtual ICollection<ProjectForm> ProjectForm { get; set; }
    }
}

在 dataTextField 中以我不想看到的方式显示“ContinentID”:

namespace Project.Models
{
    public partial class Continent
    {
        public int ContinentID { get; set; }
        public string ContinentName { get; set; }

        public virtual ICollection<ProjectForm> ProjectForm { get; set; }

    }
}

不幸的是,模型定义对我来说没有什么明显不同。

【问题讨论】:

  • 你能添加你的型号代码吗?
  • 我已修改问题以包含模型代码
  • 嗯,我什么也没看到。我可以说,这些年来我已经看到了很多怪癖和奇怪的事情,这些怪癖和奇怪的事情是关于脚手架和他们试图在引擎盖下做的自动化事情。您可以尝试将一些问题代码移至新的解决方案,并尝试查看是否可以在那里重现问题或问题是否消失。

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


【解决方案1】:

我今天偶然发现了这篇文章(有点晚了),但看到它仍然没有得到答复。

虽然我不能说明为什么脚手架在您的场景中选择使用一个字段而不是另一个字段(除非您最初在上次清理/构建项目时以不同方式编写了类/模型),但我可以说如何强制它使用特定的列。

将 DisplayColumn 属性添加到您的类。您需要在再次搭建脚手架之前进行重建以进行更改。

namespace Project.Models
{
    [DisplayColumn("ContinentName")]
    public partial class Continent
    {
        public int ContinentID { get; set; }
        public string ContinentName { get; set; }

        public virtual ICollection<ProjectForm> ProjectForm { get; set; }

    }
}

【讨论】:

    猜你喜欢
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多