【发布时间】:2021-08-03 08:35:34
【问题描述】:
给定一个
cshtml 部分位于另一个 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>
还有一个控制器,
[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);
}
还有这个模型,
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; }
}
}
}
我得到了异常
InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为“System.Collections.Generic.List`1[LeagueProject.Models.Participant]”,但此 ViewDataDictionary 实例需要“LeagueProject.Models.ViewModel”类型的模型项'。
我不知道为什么会出现错误。我是框架的新手。这适用于以前的类似项目。
【问题讨论】:
-
我也尝试在我的主 cshtml 上添加这个,我调用包含 partial::::
的选项卡 -
你能在另一个cahtml中显示包含部分的行吗
标签: c# asp.net asp.net-mvc asp.net-core