2

我从 TempData 探测整数时遇到了这个问题,因为它将 DempData["sth"] 视为对象,而不是整数本身。这是我将整数发送到 TempData 的 Create 方法:

public ActionResult Create(int CustomerId, int qSetId, int Count)
{
    qSet qset = db.qSets.Find(qSetId);
    TempData["qSetId"] = qset.Id;
    Customer customer = db.Customers.Find(CustomerId);
    TempData["CustomerId"] = customer.Id;
    List<Relation> relations = db.Relations.Where(r => r.qSetId.Equals(qSetId)).ToList<Relation>();
    Question question = new Question();
    List<Question> questions = new List<Question>();
    foreach (Relation relation in relations)
    {
        question = db.Questions.Find(relation.QuestionId);
        if (questions.Contains<Question>(question).Equals(false))
            questions.Add(question);
    }
    if (questions.Count<Question>().Equals(Count).Equals(false))
    {
        TempData["QuestionId"] = questions[Count].Id;
        TempData["QuestionType"] = questions[Count].Type;
        ViewBag["QuestionContent"] = questions[Count].Content;
        TempData["Count"] = Count + 1;
        return View();
    }
    else
    {
        return RedirectToAction("ThankYou");
    }
}

这是另一种方法,探测这些数据:

[HttpPost]
public ActionResult Create(Answer answer)
{                               
    answer.QuestionId = TempData["QuestionId"];
    answer.CustomerId = TempData["CustomerId"];

    if (ModelState.IsValid)
    {
        db.Answers.Add(answer);
        db.SaveChanges();
        return RedirectToAction("Create", new { CustomerId = TempData["CustomerId"], qSetId = TempData["qSetId"], Count = TempData["Count"] });
    }

    ViewBag.CustomerId = new SelectList(db.Customers, "Id", "eAdress", answer.CustomerId);
    ViewBag.QuestionId = new SelectList(db.Questions, "Id", "Name", answer.QuestionId);
    return View(answer);
}

错误出现在:

answer.QuestionId = TempData["QuestionId"];
answer.CustomerId = TempData["CustomerId"];

像这样去:

无法将类型“object”隐式转换为“int”。存在显式转换(您是否缺少演员表?)

有什么帮助吗?

4

3 回答 3

9

对此的解决方案称为“拆箱”。这是从objectint的直接转换:

answer.QuestionId = (int)TempData["QuestionId"];
于 2012-05-07T08:38:30.900 回答
1

我的代码中有同样的问题。

这两种解决方案都有效:

    answer.QuestionId = Convert.ToInt32(TempData["QuestionId"];

    answer.QuestionId = (int)TempData["QuestionId"];

但是,(int) 强制转换并非在每个实例中都有效,因为并非每个对象都可以隐式强制转换为 int。因此,使用 Convert.ToInt32() 更安全

于 2016-02-16T22:15:51.887 回答
0
int id = Convert.ToInt32(TempData["QuestionId"].ToString());
于 2014-09-15T20:31:47.113 回答