Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer via TempData @ C# ASP.NET MVC3 EntityFramework

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?

like image 338
smsware Avatar asked Jul 27 '26 03:07

smsware


2 Answers

The solution to this is called "unboxing". It's a straight cast from object to int:

answer.QuestionId = (int)TempData["QuestionId"];
like image 185
McGarnagle Avatar answered Jul 29 '26 15:07

McGarnagle


Both of these solutions work:

    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()

like image 42
reakt Avatar answered Jul 29 '26 16:07

reakt