脚手架MVC控制器-如何指示dataValueField和dataTextField



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如何决定向dataTextField提供哪个字段?在个别模型或DbContext中是否有我忽略的东西?我希望大陆的dataTextField是";ContinentName";这样以后当我需要删除并重新构建控制器时,我就不必手动更改它了。


编辑:

以下是模型定义:

我在上面发布的控制器模型:

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; }
}
}

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

namespace Project.Models
{
public partial class Country
{
public int CountryID { get; set; }
public string CountryName { get; set; }
public virtual ICollection<ProjectForm> ProjectForm { get; set; }
}
}

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

namespace Project.Models
{
public partial class Continent
{
public int ContinentID { get; set; }
public string ContinentName { get; set; }
public virtual ICollection<ProjectForm> ProjectForm { get; set; }
}
}

不幸的是,在模型定义中没有什么明显的不同。

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

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

将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; }
}
}

最新更新