【发布时间】: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