簡體   English   中英

MVC 5 asp.net,從控制器到視圖的viewbag無法正常工作

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

這是控制器

public ActionResult Test() {

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

} 

在Action Named Details視圖中 ,我將檢查它是否有ViewBag來顯示和顯示它:

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

但是這里的重定向工作正常,它沒有顯示我存儲在ViewBag中的消息.MessageIs

謝謝

基本上你正在做的是從你的Index方法調用方法Details ,因為你已經用id重載了你的Details動作,所以也傳遞消息:

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

然后在Details視圖中,您可以像這樣訪問該屬性:

@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();
}

您必須這樣做,因為當您重定向到另一個活動/視圖時,viewbag會丟失其值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM