在重定向到另一个操作时,您无法传递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 –