Integer via TempData @ C# ASP.NET MVC3 EntityFramework
-
06-06-2021 - |
Frage
I have this problem with probing integer from TempData as it sees DempData["sth"] as object, not as integer itself. Here is my Create method I'm sending my integer into the 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");
}
}
And here is the other method, probing this data:
[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);
}
Errors are present at:
answer.QuestionId = TempData["QuestionId"];
answer.CustomerId = TempData["CustomerId"];
And go like this:
Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?)
Any help?
Lösung
The solution to this is called "unboxing". It's a straight cast from object to int:
answer.QuestionId = (int)TempData["QuestionId"];
Andere Tipps
I had the same issue in my code.
Both of these solutions worked:
answer.QuestionId = Convert.ToInt32(TempData["QuestionId"];
and
answer.QuestionId = (int)TempData["QuestionId"];
However, the (int) cast will not work in every instance, because not every object can be implicitly cast to int. For this reason, it's safer to use Convert.ToInt32()
int id = Convert.ToInt32(TempData["QuestionId"].ToString());
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow