我在传递变量得分方面遇到了一些麻烦,这是我的Evaluation类中的一个变量,它在我的测验控制器中的[httpPost] ifstatements(评估模型)方法中初始化为属于a的视图不同类别的不同控制器。当分数大于零时,即我至少回答一个问题时,我会进入结果视图,并向我显示分数。但我在另一个名为Index的视图中打印该分数时遇到问题,该视图是LEADERBOARD类LEADERBOARD控制器中索引方法的一部分
测验控制器
public ActionResult ifStatement()
{
var evalVM = new Evaluation();
//the below is hardcoded for DEMO. you may get the data from some
//other place and set the questions and answers
var q1 = new Question { ID = 1, QuestionText = "1. Which of the following shows the correct syntax for an if statement?" };
q1.Answers.Add(new Answer { ID = 12, AnswerText = "a. if expression" });
q1.Answers.Add(new Answer { ID = 13, AnswerText = "b. if { expression }" });
q1.Answers.Add(new Answer { ID = 14, AnswerText = "c. if ( expression ){}" });
q1.Answers.Add(new Answer { ID = 15, AnswerText = "d. expression if" });
evalVM.Questions.Add(q1);
return View(evalVM);
}
[HttpPost]
public ActionResult ifStatement(Evaluation model)
{
int score = 0;
if (ModelState.IsValid)
{
using (UsersContext db = new UsersContext())
{
foreach (var q in model.Questions)
{
var qId = q.ID;
List<string> listSelectedAnswer = new List<string>();
listSelectedAnswer.Add("14");
listSelectedAnswer.Add("19");
listSelectedAnswer.Add("22");
listSelectedAnswer.Add("25");
listSelectedAnswer.Add("28");
listSelectedAnswer.Add("33");
foreach (string answer in listSelectedAnswer)
{
foreach (var answer2 in model.Questions)
{
if (answer == answer2.SelectedAnswer)
{
score = score + 3;
}
}
}
model.Score = score;
ViewBag.score = model.Score;
if (score > 0)
{
return View("results");
}
else
{
//score = 0;
//return Content("Please check all answers have been submitted!");
return Content("Error, please ensure all questions have been answered. You may use the back button to continue the Quiz."); //PRG Pattern
}
}
}
}
model.setScore(score);
return View("ThankYou");
}
排行榜控制器
public class LeaderboardController : Controller
{
UsersContext db = new UsersContext();
//
// GET: /Leaderboard/
TutorialEntities t = new TutorialEntities();
Evaluation e = new Evaluation();
public ActionResult Index()
{
// Evaluation ev = new Evaluation();
// var tutorial = t.Evaluations.ToList();
//ViewBag.Scores = t.Evaluations.Select(a => a.Score).ToList();
//ViewBag.Scores = e.getScore();
//ViewBag.Score = e.getScore();
ViewBag.Users = db.UserProfiles.ToList();
ViewBag.Scores = t.Evaluations.ToList();
return View();
}
}
索引视图
<h2>Leaderboard</h2>
@foreach (var item2 in ViewBag.Users)
{
<p>
Score: @ViewBag.Score
</p>
}
@foreach (var item in ViewBag.Users)
{
<p>
UserID: @item.UserId
<br />
UserName: @item.UserName
<br />
</p>
}
当我查看此视图时,页面上显示的所有内容都是在我的网站上注册的人的姓名和他们的ID,但得分是空白的!我似乎无法理解我已经尝试了很多方法,但它似乎无法看到在if语句方法中初始化的分数
答案 0 :(得分:0)
您的控制器设置了viewbag.scores,但您的视图是否正在尝试访问viewbag.score?