我认为这里没有万能的解决方案。
无论如何,这是我使用 jQuery 的解决方案:
1) 创建一个 MyResultModel 类来处理给用户的消息
public enum MyResultType { Info, Error }
public class MyResultModel
{
public MyResultModel( MyResultType type, string message ) {
switch ( type ) {
case MyResultType.Info: Title = "OK"; break;
case MyResultType.Error: Title = "Error!!!"; break;
}
Message = message;
}
public String Title { get; set; }
public String Message { get; set; }
}
2) 在共享文件夹中创建一个名为MyResult 的Partial View 来处理模型
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyResultModel>" %>
<div id="resultTitle"><%: Model.Title %></div>
<div id="resultMessage"><%: Model.Message %></div>
3) 为您的控制器创建和使用 BaseController 并向其中添加以下方法。该方法只是在响应中添加一个自定义的 Http Header
protected PartialViewResult PartialView( string viewName, object model, string resultHeader ) {
Response.AppendHeader( "MyHttpCustomHeader", resultHeader );
return base.PartialView( viewName, model );
}
4) 在您的操作中,完成后返回 MyResultView
[HttpPost]
public virtual ActionResult DoSomething() {
try {
//Do Something
return PartialView( "MyResult",
new MyResultModel( MyResultType.Info, "Operation Completed" ),
"HttpResultInfo" );
}
catch ( Exception ex ) {
return PartialView( "MyResult",
new MyResultModel( MyResultType.Error, ex.Message ),
"HttpResultError" );
}
}
5) 最后,使用jquery提交表单并处理结果。
$.ajax({
type: "post",
dataType: "html",
url: "your/url/here",
data: $("#myform").serialize(),
success: function (response, status, xml) {
var resultType = xml.getResponseHeader("MyHttpCustomHeader");
if (resultType == null) {
//No message do whatever you need
}
else {
//response contain your HTML partial view here. Choose your
//desidered way to display it
}
}
});
在这种情况下,您不需要在母版页上放置控件。你可以:
- 显示来自操作的视图,无需任何修改
- 使用一些花哨的消息显示技术,就像 StackOverflow 对橙色滑动消息所做的那样(在这种情况下,只需从返回的 html 中提取标题和消息)
- 使用一些花哨的 jquery 插件作为jGrowl 来显示您的消息
如果您想检查它是否是信息/错误消息,只需在 else 分支中使用 jQuery 检查自定义标头
var title = $(response).filter("#resultTitle").text();
var message = $(response).filter("#resultMessage").text();
if (resultType == "HttpResultInfo") {
showInfoMessage(title, message);
}
else if (resultType == "HttpResultError") {
showErrorMessage(title, message);
}
希望对你有帮助!