skip to Main Content

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>

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. use this

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

    in your action include category

    var model=context.Set<Work>().Iclude(c=>c.Category).FirstOrDefault(w=> w.WorkId==id);
    return View(model);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search