如何显示或显示FK“名称”或“标题”而不是FK“ ID”

时间:2019-06-11 19:42:46

标签: c# asp.net asp.net-core model

我有两个表,一个是“纪念品”表,另一个是“类别”表。来自“ Souvenirs”表的纪念品具有与“ Categoreis”表相关的FK“ CategoryID”。问题是,当我尝试在“纪念品类别”的下拉字段中添加新的纪念品时,将显示“类别ID”,而不是标题...

是否有简单的解决方案来更改它? 预先感谢。

Form Example

Souvenir.cs

using IdentityCore.Models.Product;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace IdentityCore.Models
{
    public class Souvenir
    {
        public Souvenir() : base() { }
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Price { get; set; }
        public string Description { get; set; }
        public string Image { get; set; }

        [Display(Name = "Category")]
        public int CategoryId { get; set; }
        [ForeignKey("CategoryId")]
        public Category Category { get; set; }

    }
}

Category.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace IdentityCore.Models
{
    public class Category
    {
        public Category() : base() { }
        [Key]
        public int Id { get; set; }
        public string Title { get; set; }

        public List<Souvenir> Souvenirs { get; set; }
    }
}

ApplicationDbContext.cs

using System;
using System.Collections.Generic;
using System.Text;
using IdentityCore.Models;
using IdentityCore.Models.Product;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace IdentityCore.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole,string>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<Category> Categories { get; set; }
        public DbSet<Souvenir> Souvenirs { get; set; }
        public DbSet<Supplier> Suppliers { get; set; }
    }
}

1 个答案:

答案 0 :(得分:0)

做出一个选择列表,该列表由“类别”实体填充。

在您的控制器中,从dbcontext中获取类别列表,如下所示:

using (var db = new ApplicationDbContext())
{
    return db.Categories.ToList().Select(d => new SelectListItem()
    {
        Text = d.Title,
        Value = d.Id.ToString()
    });
}

现在,在选择列表中具有“类别”,文本是标题,值是ID。这样用户可以看到文本,并返回ID。

在模型中,添加一个选择列表属性:

using System.Web.MVC

public IEnumerable<SelectListItem> CategorySelectList { get; set; }

然后在您的视图中,将类别列表替换为DropDownListFor:

@Html.DropDownListFor(model => model.CategoryID, Model.CategorySelectList, new { @class = "form-control" })