将类传递到cshtml文件时出现字典错误
本文关键字:字典 错误 文件 cshtml | 更新日期: 2023-09-27 17:57:41
我试图将两个类传递到一个cshtml文件中,但一直收到一个错误,我正在传递一个"类型为‘JavaTutorial.Models.Quiz’的模型",但此字典需要一个类型为‘Java Tutorial.Models.Evaluation’的模型项。"
我不明白,我正在创建一个单独的类,现在只是试图传入一个类,但仍然出现了错误。
我有一个类Evaluation,我试图在cshtml中调用它,但Quiz类一直在干扰,但我不知道为什么。。
cshtml:
@model JavaTutorial.Models.Evaluation
<h2>Details</h2>
<h2>Evaluation</h2>
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Questions)
<input type="submit" />
}
评估.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace JavaTutorial.Models
{
public class Evaluation
{
public List<Question> Questions { set; get; }
public Evaluation()
{
Questions = new List<Question>();
}
}
}
测验
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace JavaTutorial.Models
{
public class Quiz
{
[Key]
public int QuizId { get; set; }
public string Title { get; set; }
public int difficulty { get; set; }
public string description { get; set; }
public Genre Genre { get; set; }
}
public class Question
{
public int ID { set; get; }
public string QuestionText { set; get; }
public List<Answer> Answers { set; get; }
[Required]
public string SelectedAnswer { set; get; }
public Question()
{
Answers = new List<Answer>();
}
}
public class Answer
{
public int ID { set; get; }
public string AnswerText { set; get; }
}
/* public class Evaluation
{
public List<Question> Questions { set; get; }
public Evaluation()
{
Questions = new List<Question>();
}
}*/
/*public class ParentView
{
public Quiz Quiz { get; set; }
public Question Question { get; set; }
public Answer Answer { get; set; }
public Evaluation Evaluation{ get; set; }
}
*/
/*
* using (Html.BeginForm())
{
@Html.EditorFor(x => x.Evaluation.Questions)
<input type="submit" />
}*/
}
控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JavaTutorial.Models;
//using ViewModels;
namespace JavaTutorial.Controllers
{
public class QuizController : Controller
{
//
// GET: /Quiz/
TutorialEntities storeDB = new TutorialEntities();
public ActionResult Details(int id)
{
var quiz = storeDB.Quizzes.Find(id);
return View(quiz);
}
您已经在视图中设置了模型:
@model JavaTutorial.Models.Evaluation
但你没有通过这个模型:
JavaTutorial.Models.Quiz
View期望模型类评估,但您通过了测验类
如果你想在视图中通过测验模型更改,如下所示:
@model JavaTutorial.Models.Quiz
如果要传递两个模型,请创建一个viewmodel,并将其放在解决方案中名为ViewModels的文件夹中。
public class MyViewModel
{
public List<Question> Questions { set; get; }
public List<Quiz> Quizzes{ set; get; }
public List<Answer> Asnwers { set; get; }
}
将视图模型传递给您的视图,并设置如下视图:
@model JavaTutorial.ViewModels.MyViewModel