C# 我想向视图asp.net mvc传递一个可变表单控制器操作

C# 我想向视图asp.net mvc传递一个可变表单控制器操作,c#,asp.net,asp.net-mvc,razor,C#,Asp.net,Asp.net Mvc,Razor,我想要一种方法,使我能够将变量数据而不是类数据从家庭控制器中的动作传递到视图,而不是像viewbag之类的非常简单的方法,我搜索了一整天,看到了viewdata viewbag tempdata会话,我想做的是我有一个简单的asp.net mvc程序,可以及时问我10个问题表中,当我回答完10个问题后,它会将我重定向到一个viewindex,其中会说“恭喜您正确回答了10个问题中的正确答案,我无法在代码中找到答案”,因此以下是控制器操作: [HttpPost] public Action

我想要一种方法,使我能够将变量数据而不是类数据从家庭控制器中的动作传递到视图,而不是像viewbag之类的非常简单的方法,我搜索了一整天,看到了viewdata viewbag tempdata会话,我想做的是我有一个简单的asp.net mvc程序,可以及时问我10个问题表中,当我回答完10个问题后,它会将我重定向到一个viewindex,其中会说“恭喜您正确回答了10个问题中的正确答案,我无法在代码中找到答案”,因此以下是控制器操作:

[HttpPost]
    public ActionResult Question(Models.QuestionVM model)
    {
        int? cAnswers = model.CAnswers;
        ViewBag.CA = cAnswers;
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        int correctAnswer = model.Number1 * model.Number2;
        if (model.SelectedAnswer == correctAnswer)
        {
            cAnswers += 1; //here is the code that must increment the number of correct answers whenever the useranswer is equal to correctanswer
        }
        if (model.ID < 10)
        {
            return RedirectToAction("Question", new { id = ++model.ID });
        }
        else
        {
            return RedirectToAction("Index"); // the method that displays the final results
        }
    }
以及我要将变量传递给索引的视图:

@{
ViewBag.Title = "Home Page";
}

<div style="text-align: center;">
<h1 style="font-size:125px; color: darkorange; font-weight: 900; 
">Congratulations!</h1>
<h2 style="font-size:75px; color: darkorange; font-weight: 900; ">You Have 
Answered @ViewBag.CA From 10 Questions</h2>
</div>
以及问号VM类:

public class QuestionVM
{
    public int ID { get; set; } // the question number
    public int Number1 { get; set; }
    public int Number2 { get; set; }
    public List<int> PossibleAnswers { get; set; }
    [Display(Name = "Answer")]
    [Required(ErrorMessage = "Please select an answer")]
    public int? SelectedAnswer { get; set; }
    public int? CAnswers { get; set; } // Here is the variable that I'm trying to increment
}

ViewBag不适用于重定向。重定向到其他操作方法时,需要使用TempData

TempData["CorrectAnswers"] = 4;
return RedirectToAction("Index");
在索引操作或视图中,从TempData[CorrectAnswers]读取值


实现此目标的一种方法是,在重定向之前,将值存储在会话中:

Session["cAnswers"] = cAnswers;
return RedirectToAction("Index"); 
然后为索引创建另一个操作,从会话中获取值并将其填充到ViewBag中:

public ActionResult Index()
{
    ViewBag.CA = Session["cAnswers"];
    return View();
}

@Shyju它已经在返回线之前了,或者你是说另一件事吗?那么什么具体不起作用?@Shyju当我运行代码时,它会让我进入索引页并说恭喜!你已经回答了,但这里什么都没有,但我想从这里得到10个问题的正确答案。我已经将viewbag.CA更改为tempData[CA],并且仍然没有在索引视图中显示任何内容。如果你能说得更清楚,以便我能解决它,那将是一个了不起的tempData[CA]=TempData[CA]。您是否也在视图中进行了更改?您编写的代码应该在哪里编写?是,在重新调整重定向之前,我已更改了视图设置,并在操作方法中设置了TempData
public ActionResult Index()
{
    ViewBag.CA = Session["cAnswers"];
    return View();
}