Home > database >  ASP.NET MVC how to get name from another model by Id
ASP.NET MVC how to get name from another model by Id

Time:10-27

I have got one question, how can I get category name in details.cshtml by foreign key - CategoryId in work model?

work.cs

using System;
using System.ComponentModel.DataAnnotations;

namespace InfoKiosk.Domain.Entities
{
    public class Work
    {
        public int WorkId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int CategoryId { get; set; }
        public Category Category { get; set; }
    }
}

category.cs

    public class Category
    {
        public int CategoryId { get; set; }
        public string Name { get; set; }
    }

The names of categories I choose from dropdownlist which one I populate from ViewBag.

details.cshtml


<dt>
    <strong>@Html.DisplayNameFor(model => model.Category):</strong> @Html.DisplayFor(model => model.???)
</dt>

CodePudding user response:

 you can try: 
   `[ForeignKey("Category ")]
    public int CategoryId { get; set; }
    public Category Category { get; set; }`
  

CodePudding user response:

You can pass this in a ViewBag to the the view maybe from Controller :

string NameCategory = from c in context.Category
where c.CategoryId == work.categoryId
select c.Name
  • Related