MVC3 Controller Action Result 'Remember' P

2019-06-10 06:25发布

问题:

I have two action results in my Controller. Overview and About.

public ActionResult Overview(int id)
{
    return View(new OverviewModel() { Project = db.People.Find(id) });
}

public ActionResult About(int id)
{
    return View(new AboutModel() { Project = db.People.Find(id) });
}

I would like to remember the id that was passed in to Overview and use it on the About as the default. I don't know how to keep this Id constant while the user switches tabs from Overview to About.

回答1:

You can try storing the id in TempData. Maybe something like this (not tested)

public ActionResult Overview(int id)
{
    TempData["YourId"] = id;
    return View(new OverviewModel() { Project = db.People.Find(id) });
}

public ActionResult About(int? id)
{
    id = id ?? int.Parse(TempData["YourId"].ToString());
    return View(new AboutModel() { Project = db.People.Find(id) });
}


回答2:

You can also use hidden html attribute if this data is not sensitive. it worked wonders for us and it saved us alot of processing power.