Reputation: 7
Given a
cshtml
partial within another cshtml
@model List<Participant>;
@{
if(Model != null)
{
foreach(Participant i in Model)
{
<p>@i.ParticipantFirstName</p>
}
}
if(Model == null)
{
<p>placeholder:: the list is empty</p>
}
}
<p>test</p>
and a controller,
[HttpGet]
[Route("dashboard")]
public IActionResult Dashboard()
{
if(HttpContext.Session.GetInt32("UserId") == null)
{
return RedirectToAction("Index","Home");
}
ViewBag.loggedinUser = HttpContext.Session.GetInt32("UserId");
HttpContext.Session.SetInt32("DashboardTab", 0);
List<Participant> allParticipants = db.Participants.Include(i=>i.Parent).ToList();
return View("Dashboard", allParticipants);
}
and this model,
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace LeagueProject.Models
{
public class ViewModel
{
private Context db;
public ViewModel(Context context)
{
db = context;
}
public Participant participant { get; set; }
public class Participant
{
[Key]
public int ParticipantId { get; set; }
[Required(ErrorMessage = "is required")]
[MinLength(2, ErrorMessage = "must be at least 2 characters")]
public string ParticipantFirstName { get; set; }
[Required(ErrorMessage = "is required")]
[MinLength(2, ErrorMessage = "must be at least 2 characters")]
public string ParticipantLastName { get; set; }
[Required(ErrorMessage = "is required")]
public string ParticipantGender { get; set; }
// [Required(ErrorMessage = "is required")]
// [Range(8, 20, ErrorMessage="this league if roages 8-19")]
// public int ParticipantAge { get; set; }
[Required(ErrorMessage="Need a date of birth")]
[DataType(DataType.Date)]
public System.DateTime ParticipantDOB { get; set; }
public int UserId { get; set; }
public User Parent { get; set; }
public List<MMLeagueParticipant> allLeagues { get; set; }
}
}
}
I get the exception
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List`1[LeagueProject.Models.Participant]', but this ViewDataDictionary instance requires a model item of type 'LeagueProject.Models.ViewModel'.
I can't figure out why I'm getting the error. I'm new to the framework. This worked on a previous project on something similar.
Upvotes: 0
Views: 54
Reputation: 8459
It should be List<Participant>
in the ViewModel:
public class ViewModel
{
//...
public List<Participant> participants { get; set; }
}
Then in your controller , return this ViewModel to the main view.
[HttpGet]
[Route("dashboard")]
public IActionResult Dashboard()
{
if(HttpContext.Session.GetInt32("UserId") == null)
{
return RedirectToAction("Index","Home");
}
ViewBag.loggedinUser = HttpContext.Session.GetInt32("UserId");
HttpContext.Session.SetInt32("DashboardTab", 0);
List<Participant> allParticipants = db.Participants.Include(i=>i.Parent).ToList();
var viewmodel = new ViewModel();
viewmodel.participants = allParticipants;
return View("Dashboard", viewmodel);
}
Upvotes: 0