在我目前的MVC项目中,我有一个控制器,其中包含以下方法:
public ActionResult Index(string answer)
{
using (S3WEntities1 ent = new S3WEntities1())
{
afqList.Question = ent.Questions.Where(w => w.QuQuestionId == 1).Select(s => s.QuQuestion).FirstOrDefault().ToString();
afqList.Answers = ent.Answers.Where(w => w.AnsQuestionId == 1).Select(s => s.AnsAnswer).ToList();
}
return View(afqList);
}
然而,这种方法重复了5次,唯一的区别是(w => w.QuQuestionId == x)
和(w => w.AnsQuestionId == x)
中的数字发生了变化,并且每种方法都有5种不同但仍然相似的视图。我如何使这个代码比使用5个几乎相同的方法更好很多,但是仍然有不同的观点?提前谢谢!
修改 我还要提一下,在每种方法中,相应的视图都有一个
@using (Html.BeginForm("Question3", "ControllerName", "FormMethod.Post))
所以需要调用不同的方法,这些方法基于下一个方法,并在视图中说明。
答案 0 :(得分:1)
将数字替换为x,将作为参数传递
public ActionResult Index(string answer, int x)
{
using (S3WEntities1 ent = new S3WEntities1())
{
afqList.Question = ent.Questions.Where(w => w.QuQuestionId == x).Select(s => s.QuQuestion).FirstOrDefault().ToString();
afqList.Answers = ent.Answers.Where(w => w.AnsQuestionId == x).Select(s => s.AnsAnswer).ToList();
}
return View(afqList);
}
答案 1 :(得分:1)
首先添加到您的模型中:
public string NextQuestion { get; set; }
然后您可以在行动中使用它并查看:
public ActionResult Index(string answer, int questionId)
{
using (S3WEntities1 ent = new S3WEntities1())
{
afqList.Question = ent.Questions.Where(w => w.QuQuestionId == questionId).Select(s => s.QuQuestion).FirstOrDefault().ToString();
afqList.Answers = ent.Answers.Where(w => w.AnsQuestionId == questionId).Select(s => s.AnsAnswer).ToList();
}
afqList.NextQuestion = string.Format("Question{0}", questionId + 1);
return View(afqList);
}
现在在视图中:
@using (Html.BeginForm(afqList.NextQuestion, "ControllerName", "FormMethod.Post))