序列不包含MVC元素

时间:2018-02-10 18:07:59

标签: c# linq

我正在尝试使用链接(路由)和Razor重定向到另一个页面。当用户登录时,检查他们是否完成了调查。如果他们尚未完成调查,则会将其重定向到“继续”视图。然后,他们可以点击“继续”链接,这会将他们带回到他们离开的地方。

其他一切正常,但我无法从“继续”视图重定向到“问题”视图,而不会获得“序列不包含任何元素错误”

剃刀:

@{
   ViewBag.Title = "Continue";
}

<h2>Do you want to continue registration</h2>
@Html.ActionLink(
"Continue",
"Question",
"PreRegistration",
new
{
    questionId = 0,
    direction = "Next"
} ,
null
)

以下是来自我的控制器的动作

public ActionResult Question(int? questionId, string direction)
    {
        var a = (from x in db.Progress.ToList() where x.fldUserID == User.Identity.GetUserId() select x);
        var currentPosition = a.FirstOrDefault().fldCurrentQuestionId;
        var registrationCompleted = a.FirstOrDefault().fldRegistrationCompleted;
        var progressId = a.FirstOrDefault().Id;

        var maxPosition = (from x in db.Question select x.Id).ToList().Last();
        var minPosition = (from x in db.Question select x.Id).ToList().First();

        if (!registrationCompleted && direction == "Back")
            if (questionId == null || questionId < minPosition)
            questionId = minPosition;

        if (!registrationCompleted && direction == "Next")
        {
            if (questionId == maxPosition)
                registrationCompleted = true;

            var q = db.Question.Find(questionId);
            var p = db.Progress.Find(progressId);

            var progressModel = new RegistrationViewModel {Questions = q, Progress = p};
            p.fldCurrentQuestionId = questionId.Value;
            p.fldRegistrationCompleted = registrationCompleted;
            p.fldTimeStamp = System.DateTime.Now;
            p.fldUserID = User.Identity.GetUserId();

            db.Progress.AddOrUpdate(p);
            db.SaveChanges();

            return View(progressModel);
        }

        return Redirect("/PreRegistration/Completed/");

此外,我注意到当我在“继续”视图上的链接上方悬停时,它显示localhost:53329/PreRegistration/Question?questionId=0,我希望看到localhost:53329/PreRegistration/Question/0/Next

我无法理解为什么它说Sequence contains no elements我已将所有代码更改为FirstOrDefault(),我仍然会收到错误消息。我也不明白为什么URL只显示一个元素/

错误的前几行如下:

 System.Linq.Enumerable.Last(IEnumerable`1 source) +318
 Foodsnap.Controllers.PreRegistrationController.Question(Nullable`1 
 questionId, String direction) +290

非常感谢任何指导。

0 个答案:

没有答案