ViewModel Basics

Dean Everhart 1,541 Reputation points
2023-05-01T16:42:33.9533333+00:00

Trying to display data from a viewmodel within the action method of a model (Item)

models
Item property name: "Text"
Reference property name: "Source"

ViewModel
ItemReference

Controller

 Item                                     <- ItemReference Action Method within Item Controller  

**View
**
@model IEnumerable<Note.Models.View.ItemReference>

 DisplayFor does not (red underline below)

User's image

Models

Item

namespace Note.Models
{
    public class Item
    {
        public int Id { get; set; }

        public string? Text { get; set; }

Reference

namespace Note.Models
{
    public class Reference
    {
        public int Id { get; set; }

        public string? Source { get; set; }

ViewModels - ItemReference

using System.Net;

namespace Note.Models.View
{
    public class ItemReference
    {
        public Item Item { get; set; }
        public Reference Reference { get; set; }
    }
}

View

 DisplayNameFor seems to resolve properly  
 DisplayFor does not (red underline below)

User's image

Controller - Item Controller / ItemReference (Viewmodel) Action Method


namespace Note.Controllers
{ 
    public class ItemController : Controller                        <- Item Controller
    {
        private readonly ApplicationDbContext _context;

        public ItemController(ApplicationDbContext context)
        {
            _context = context;
        }
       

 		// GET: Item
        public async Task<IActionResult> Index()
        {
              return _context.Item != null ? 
                          View(await _context.Item.ToListAsync()) :
                          Problem("Entity set 'ApplicationDbContext.Item'  is null.");
        }

        // GET: Item
        public async Task<IActionResult> ItemReference()          <- ViewModel Method
        {
            return _context.Item != null ?
                        View(await _context.Item.ToListAsync()) :
                        Problem("Entity set 'ApplicationDbContext.Item'  is null.");
        }

Environment: Net Core 6 MVC, Visual Studio Community 2022 (64 bit), WIndows 11

Developer technologies ASP.NET ASP.NET Core
Developer technologies ASP.NET Other
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2023-05-01T17:11:03.8466667+00:00

    The syntax is item.Item.Text, item.Item.Id, and item.Reference.Source. Keep in mind, Visual Studio's intellisense displays a list of the properties.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.