我有从TempData探测整数的问题,因为它将DempData [“sth”]视为对象,而不是整数本身。这是我的Create方法,我将整数发送到TempData:
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'。存在显式转换(您是否错过了演员?)
任何帮助?
答案 0 :(得分:8)
对此的解决方案称为“拆箱”。它是从对象到 int 的直接演员:
answer.QuestionId = (int)TempData["QuestionId"];
答案 1 :(得分:1)
我的代码中遇到了同样的问题。
这两种解决方案都有效:
answer.QuestionId = Convert.ToInt32(TempData["QuestionId"];
和
answer.QuestionId = (int)TempData["QuestionId"];
但是,(int)强制转换在每个实例中都不起作用,因为并非每个对象都可以隐式转换为int。因此,使用Convert.ToInt32()
会更安全答案 2 :(得分:0)
int id = Convert.ToInt32(TempData["QuestionId"].ToString());