[英]ASP.Net MVC random, Controllers and views
我在创建ASP.NET MVC
程序时遇到了麻烦,该程序将随机选择一个学生并随机选择一个问题,由于某种原因,我无法在.cshtml文件中使用它。 难道我做错了什么? 我也得到这个错误
使用QuizProgramMVC.Models,“传递到字典中的模型项的类型为'QuizProgramMVC.Models.Student',但是此字典要求模型项的类型为'QuizProgramMVC.Models.StudentQuestion'。”
控制者
public class QuizController : Controller
{
public QuizController TheQuiz { get; set; }
// GET: Quiz
public ActionResult Index()
{
StudentQuestion sq = new StudentQuestion();
return View(sq);
}
public ActionResult QuizProgram()
{
Student program = new Student();
return View(program);
}
}
视图
@model QuizProgramMVC.Models.StudentQuestion
@using QuizProgramMVC.Models;
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>QuizProgram</title>
</head>
<body>
<div>
<h1>Quiz Program</h1>
<div class="row">
<div class="col-md-6">
<table class="table table-condensed">
<thead>
<tr>
<th>Question</th>
<th>Answer</th>
</tr>
</thead>
<tbody>
@foreach (Question q in Model.Questions)
{
<tr>
<td>
@q.Quest
</td>
<td>
@q.Answer
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<br/>
<div class="row">
<div class="col-md-6">
<table class="table table-condensed">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
@foreach (Student s in Model.Students)
{
<tr>
<td>
@s.FirstName
</td>
<td>
@s.LastName
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<br/>
@using (Html.BeginForm())
{
<div>
Type Answer: <input id="param1" name="param1" type="text" />
<br />
<input type="submit" value="Submit" />
</div>
}
</div>
</body>
</html>
问题是您正在使用不同的模型调用同一视图页面。
public ActionResult QuizProgram()
{
Student program = new Student();//Here you need to pass the StudentQuestion to the view.
return View(program);
}
通过QuizProgram()调用上述视图页面(.cshtml)会引发错误,因为在该视图页面中您将模型定义为
@model QuizProgramMVC.Models.StudentQuestion
它不允许使用其他ViewModel,因为它是强类型的 View。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.