简体   繁体   中英

MVC 5 asp.net, viewbag from controller to view is not working

this is the controller

public ActionResult Test() {

@ViewBag.TheMessageIs = "this is the message";
return RedirectToAction("Details", new { id = theId});

} 

on the view of Action Named Details I will check if it has the ViewBag to show and show it:

@{
  if(ViewBag.TheMessageIs != null){
         @ViewBag.TheMessageIs
  }
}

but here the redirection is working fine to the page, it's not show the message I have stored in ViewBag.TheMessageIs

thanks

Basically what you're doing is invoking the method Details from your Index method and since you're already overloading your Details action with an id , pass it the message as well:

public ActionResult Index()
{
    //ViewBag.TheMessageIs = "this is the message";
    return RedirectToAction("Details", new { id = 1, TheMessageIs = "this is the message" });
}

public ActionResult Details(int id, string TheMessageIs)
{
    ViewBag.TheMessageIs = TheMessageIs;
    return View();
}

Then in the Details view you can access the property like this:

@ViewBag.TheMessageIs
public ActionResult Test() {
 TempData["shortMessage"] = "MyMessage";
 return RedirectToAction("Details", new { id = theId});
}

public ActionResult Details {
 //now I can populate my ViewBag (if I want to) with the TempData["shortMessage"] content
  ViewBag.TheMessageIs = TempData["shortMessage"].ToString();
  return View();
}

You have to do it like this since the viewbag looses its value when you redirect to another active / view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM