[英]Incrementing and Decrementing a querystring parameter?
在我當前的MVC項目(我在同一個項目中問的第三個問題!)中,我有一個“着陸頁”,只需單擊一下按鈕,它就會重定向到以下頁面URL:
本地主機:111111 / AccountsFinance / Index?questionId = 1
我可以手動編輯URL並更改Id = 2 ,這確實會更改顯示的內容,但是我當然需要一個按鈕來執行此操作。
在此視圖中,我具有以下內容:
@using (Html.BeginForm("Index", "AccountsFinance", FormMethod.Post))
{
//SOME CODE
<input class="btn btn-success" type="submit" value="Back" />
<input class="btn btn-success" type="submit" value="Next" />
}
這是我的控制器代碼,不確定這個問題是否必要,但最好不要包含它!
public AccountsFinanceQuestion afqList = new AccountsFinanceQuestion();
public ActionResult Index(string ans)
{
int qId = int.Parse(Request.QueryString["questionId"]);
using (S3WEntities1 ent = new S3WEntities1())
{
afqList.Question = ent.Questions.Where(w => w.QuQuestionId == qId).Select(s => s.QuQuestion).FirstOrDefault().ToString();
afqList.Answers = ent.Answers.Where(w => w.AnsQuestionId == qId).Select(s => s.AnsAnswer).ToList();
}
return View("Index", afqList);
}
因此,我將如何遞增/遞減查詢字符串的questionId = X部分,以使其移至下一個問題/上一個問題。 在同一控制器上以相同方法在同一視圖中進行所有操作。 我也理解,對於第一個問題,如果用戶單擊,這可能無法很好地解決,因為URL完全不同,但這是以后要提到的問題。
首先,您不需要手動解析查詢字符串參數-默認的活頁夾將為您完成。 只需用相應的名稱定義方法參數即可。 例如
public ActionResult Index(int questionId)
其次,似乎您正在查看某個問題的詳細信息。 因此,我認為Index不適合這樣做。 我建議使用“詳細信息”或“編輯”:
public ActionResult Details(int questionId)
關於下一個和上一個問題的鏈接-您只需在視圖中生成操作鏈接即可:
@Html.ActionLink("Back", "Details", new { questionId = Model.QuQuestionId - 1 }
@Html.ActionLink("Next", "Details", new { questionId = Model.QuQuestionId + 1 })
還要注意,您的方法有幾個問題:
解決這些問題的最簡單方法-將上一個和下一個問題的ID傳遞給視圖。 您可以為此使用模型屬性,也可以使用ViewBag
:
ViewBag.PrevQuestionId = ent.Questions
.Where(q => q.QuQuestionId < questionId)
.OrderByDescending(q => q.QuQuestionId)
.Select(q => q.QuQuestionId)
.FirstOrDefault();
然后,您可以在“視圖”中有條件地添加指向上一個問題的鏈接:
@if (ViewBag.PrevQuestionId > 0) {
@Html.ActionLink("Back", "Details", new { questionId = ViewBag.PrevQuestionId }
}
與下一個問題相同
您可以在控制器中執行以下操作:
int qId = int.Parse(Request.QueryString["questionId"]);
Response.RedirectToRoute("current-route?questionId=" + qId++);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.