在重定向到另一个操作时,您不能传递 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);
}
}
此时您只需在Tempdata 中注册新的GlobalMessage,如下所示:
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");
}
}
}
接下来是如何在视图中显示数据的最后一步:
我个人使用弹出窗口或模态窗口来执行此操作:例如,在 bootstrap 中,您会编写如下内容:
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 panel-@globalMessage .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 btn-@globalMessage .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>
}
这个例子是为了展示如何让系统显示不同的消息。简而言之,随心所欲!