在重定向到另一個操作時,您無法傳遞ViewBag
值。如果你是在同一個控制器可以使用TempData
傳遞會話中的值,否則你可以傳遞消息作爲參數來RedirectionResult
象下面這樣:
return RedirectToAction("Index", new {message="Your Message"});
,然後拿回來這樣的:
public ActionResult Index(string message)
{
ViewBag.ViewBag.InsertionResult = message;
return View();
}
這是如何傳遞消息,但我會建議像這樣的一般方法:
使用BaseController
,所有控制器從這個繼承:
在這裏,您可以制定一個自定義邏輯,如何處理全局消息,如錯誤消息,通知消息,信息消息等。
對於您需要創建一個模型,如下圖所示:
我保持簡單在這裏:
public class GlobalMessage
{
public string Message { get;set;}
public AlertType AlertType {get;set;}
}
public enum AlertType
{
Success, Info, Error, Danger//etc
}
在BaseController
你有這樣的事情:
public abstract class BaseController : Controller
{
protected GlobalMessage GlobalMessage;
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result is ViewResult)
{
if (GlobalMessage!= null)
{
filterContext.Controller.ViewBag.GlobalMessage = GlobalMessage;
}
else
{
GlobalErrorViewModel globalErrorModelView = TempData["GlobalMessage"] as GlobalMessage;
if (globalErrorModelView != null)
{
filterContext.Controller.ViewBag.GlobalErrorViewModel = globalErrorModelView;
}
}
}
base.OnActionExecuted(filterContext);
}
}
在這一刻,你只需要註冊新的GlobalMessage
在Tempdata
如下:
public PeopleController : BaseController
{
[HttpPost]
public ActionResult Create(PersonModels person)
{
try
{
// TODO: Add insert logic here
//Adding to database and holding the response in the viewbag.
string strInsertion = ConnectionModels.insertPerson(person);
TempData["GlobalMessage"] = new GlobalMessage{ AlertType = AlertType.Info, Message = "You have successfully added a new person" }
return RedirectToAction("Index");
}
catch
{
return View("Index");
}
}
}
當年這裏是最後一步如何在視圖中顯示的數據:
我個人使用彈出窗口或模態窗口,要做到這一點:例如在bootstrapp你會寫是這樣的:
GlobalMessage globalMessage = ViewBag.GlobalMessage as GlobalMessage;
@if (globalMessage != null)
{
<!-- Modal -->
<div class="modal fade" id="globalMessage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content [email protected] .AlertType.ToString().ToLower() remove-border-radius">
<div class="modal-header panel-heading">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p class="h-text-primary">@Html.Raw(globalMessage .Message)</p>
</div>
<div class="modal-footer">
<button type="button" class="btn [email protected] .AlertType.ToString().ToLower() remove-border-radius" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
}
觸發如果有消息的模式:
@if (globalMessage != null)
{
<script type="text/javascript">
$(document).ready(function() {
$('#globalMessage').modal('show');
});
</script>
}
這個例子是爲了告訴你如何使一個系統來顯示不同的信息。無論你想要什麼,總之,
確切的問題在這裏回答:https://stackoverflow.com/questions/14497711/set-viewbag-before-redirect –