将数据传递给控制器​​中的其他ActionMethod

时间:2017-03-23 10:34:36

标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

我在控制器中有几种动作方法

首先,我在这里接收Interview_id并将其写入TempData。

  [HttpPost]
    public ActionResult WelcomeScreen(Interview interview)
    {
        db.Interview.Add(interview);
        db.SaveChanges();
        Int32 id = interview.Interview_Id;
        TempData["id"] = id;
        return RedirectToAction("Index", "Questions");
    }

我在这里设置了断点TempData["id"] = id;并看到id有价值。

这是下一个方法,这里我需要将数据从TempData写入表。

    [HttpPost]
    public ActionResult Index(string question1, string question2, string question3, string question4, string question5, string question6, string question7, string question8, string question9, string question10,Int32 id)
    {
        QuestionBlock question = new QuestionBlock
        {
            Question1 = question1,
            Question2 = question2,
            Question3 = question3,
            Question4 = question4,
            Question5 = question5,
            Question6 = question6,
            Question7 = question7,
            Question8 = question8,
            Question9 = question9,
            Question10 = question10,
            Interview_Id = (int)TempData["id"],
        };
        db.QuestionBlocks.Add(question);
        db.SaveChanges();
        return Json(new { Result = "Success", Message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
    }

但我有错误。

  

参数字典包含参数' id'的空条目。非可空类型的System.Int32'方法' System.Web.Mvc.ActionResult索引

我做错了什么?

更新

获取方法

 // GET: Questions
    public ActionResult Index()
    {
        ViewBag.Question1 = new SelectList(db.Questions, "question", "question");
        ViewBag.Question2 = new SelectList(db.Questions, "question", "question");
        ViewBag.Question3 = new SelectList(db.Questions, "question", "question");
        ViewBag.Question4 = new SelectList(db.Questions, "question", "question");
        ViewBag.Question5 = new SelectList(db.Questions, "question", "question");
        ViewBag.Question6 = new SelectList(db.Questions, "question", "question");
        ViewBag.Question7 = new SelectList(db.Questions, "question", "question");
        ViewBag.Question8 = new SelectList(db.Questions, "question", "question");
        ViewBag.Question9 = new SelectList(db.Questions, "question", "question");
        ViewBag.Question10 = new SelectList(db.Questions, "question", "question");
        ViewBag.Vacancy = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
        return View(db.Questions.ToList());
    }

2 个答案:

答案 0 :(得分:1)

只需将id传递给索引即可转到

 return RedirectToAction("Index", "Questions", int id here);`

答案 1 :(得分:1)

你可以像下面那样传递id字段:

return RedirectToAction("Index", "Questions", new { id = interview.Interview_Id });