2016-02-12 133 views
0

在我目前的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种不同但仍相似的观点。我怎样才能使这个代码lot好于有5个几乎相同的方法,但仍然有不同的意见?提前致谢!

编辑: 我还要提到的是,在每一种方法,相应的视图具有

@using (Html.BeginForm("Question3", "ControllerName", "FormMethod.Post)) 

,因此需要根据调用不同的方法哪一个随之而来的,并在陈述观点。

回答

1

更换,这将作为参数

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

首先添加到您的模型通过用X数量:

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); 
    }

Now in the View:

@using (Html.BeginForm(afqList.NextQuestion, "ControllerName", "FormMethod.Post))
+0

有趣......但你可以只处理视图中的逻辑...但喜欢这个想法 – Seabizkit

+0

我的不好,认为他想要不同的看法,但方法相同。所以我有点结合。 – SynerCoder

+0

@SynerCoder是的,我知道。我认为这与我所需要的非常接近。问题是,有没有办法改变下一个要在视图中调用的方法的下一个方法? (我对我的问题的最新编辑可能更好地解释这一点) –

相关问题