user16014328
user16014328

Reputation:

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

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>

Upvotes: 1

Views: 1562

Answers (2)

Serge
Serge

Reputation: 43959

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

Upvotes: 0

Coder-Meca
Coder-Meca

Reputation: 409

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

Upvotes: 1

Related Questions