我通過JavaScript處理程序(我使用jQuery)將表單提交給ASP.NET MVC 3服務器,並從另一個JavaScript處理程序中的服務器接收錯誤響應。我想知道的是,我應該如何在視圖中顯示來自表單提交的錯誤消息?我寧願使用一些標準的ASP.NET MVC 3 idiom /構造。什麼是在ASP.NET MVC 3視圖中顯示來自JavaScript(jQuery)的錯誤的推薦方式?
編輯
注意,我想從服務器顯示錯誤消息,在JavaScript錯誤處理功能接收。
我通過JavaScript處理程序(我使用jQuery)將表單提交給ASP.NET MVC 3服務器,並從另一個JavaScript處理程序中的服務器接收錯誤響應。我想知道的是,我應該如何在視圖中顯示來自表單提交的錯誤消息?我寧願使用一些標準的ASP.NET MVC 3 idiom /構造。什麼是在ASP.NET MVC 3視圖中顯示來自JavaScript(jQuery)的錯誤的推薦方式?
編輯
注意,我想從服務器顯示錯誤消息,在JavaScript錯誤處理功能接收。
你可以去純MVC方式:http://www.asp.net/mvc/tutorials/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript
向下滾動到「啓用客戶端驗證。」
在你看來,你將有代碼看起來像這樣:
@Html.TextBoxFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
UPDATE
似乎OP感興趣的定製消息。這種定製消息沒有任何MVC構造。你最好的選擇就是創建你自己的消息區域並在你的回調函數中寫入消息。不應該太複雜!
$.ajax(..., function(data) {
$('#errors').append('<p>' + data + '</p>');
});
假設你正在使用jQuery的驗證帶有MVC解決方案模板,在你的JavaScript處理程序,你將不得不錯誤添加到驗證。有一個showErrors
method on validator。
在客戶端:
var formSubmitCallback = function(result){
var validator = $(this).data('validator');
if(!result.IsValid && validator)
validator.showErrors(result.Errors); // uses jquery validator to highlight the fields
// process the rest of the result here
// if result.Action == ActionTypes.Redirect
// location.href = result.Url
// etc
}
現在,我不得不從服務器規範的結果對象返回與{ "FieleName": "Error Message" }
格式化的JSON對象。我在服務器端建立了幾個Controller
和ViewModel
擴展來實現這一點。
在服務器端:
public ActionResult SomeAction(Model someModel){
if(ModelState.IsValid)
// save
else
// other stuff
// always return this.AjaxSubmit.
// Extension function will add Errors, and IsValid to the response data
return this.AjaxSubmit(new ClientAction{
Action = ClientActionType.Redirect,
Url = "/Some/Redirect/Route"
});
}
注:回頭看這現在我也寫一點自定義代碼,使其工作。我最終將添加客戶端和服務器代碼,以及github上的示例。但這是總體思路。
服務器類和擴展你需要低於
// GetAllErrors is a ModelState extension to format Model errors for Json response
public static Dictionary<string, string> GetAllErrors(this ModelStateDictionary modelState)
{
var query = (from state in modelState
where state.Value.Errors.Count > 0
group state by state.Key into g
select new
{
FieldName = g.Key,
FieldErrors = g.Select(prop => prop.Value.Errors).First().Select(prop => prop.ErrorMessage).ToList()
});
return query.ToDictionary(k => k.FieldName, v => string.Join("<br/>", v.FieldErrors));
}
// Controller result extension to return from actions
public static JsonResult AjaxSubmit(this Controller controller, ClientAction action)
{
if (controller == null) return new JsonResult { Data = action };
var result = new AjaxSubmitResult
{
Errors = controller.ModelState.GetAllErrors(),
IsValid = controller.ModelState.IsValid,
ClientAction = action
};
return new JsonResult{ Data = result };
}
// Action to perform on the client after a successful, valid response
public class ClientAction
{
public ClientActionType Action { get; set; }
public string Url { get; set; }
public string Function { get; set; }
public object Data { get; set; }
public Dictionary<string, string> Updatables { get; set; }
}
public enum ClientActionType
{
Redirect,
Ajax,
Function,
Modal,
Message,
FunctionAndMessage
}
服務器應具有標準化的消息作出響應。該消息可能包含一個完整的錯誤消息(HTML),然後你就可以在空白的div是你_Layout
頁面的一部分顯示:
function(response) {
if(response.Status === "error") {
$("#errorContainer").html(response.ErrorHtml);
} else {
// the success handler
}
}
的好處是,你可以執行一個比較規範的錯誤消息再現上服務器。當然,你也可以將它們顯示爲js popups /模式對話框等。
錯誤消息的格式是通過CSS完成的,它可以非常一般地應用於#errorContainer
及其內容。
您可能想爭辯說,使用服務器上的純文本進行響應並通過JS在客戶端添加任何html會更清潔。這也是可能的,並且可能使用'真正'的REST API更好地工作。但是,它不允許使用帶格式的錯誤消息(例如,使用鏈接等)
我在過去回答了類似的問題,用於添加錯誤消息。
MVC Validation Summary manipulation with JS and Dynamic DOM elements
既然你要什麼我假設是你已經知道JavaScript方法從服務器回來的錯誤,只需添加
var ul = $("#validationSummary ul"); ul.append("<li>Custom Error Message</li>")
我做到這一點的方法是:
創建基本控制器類並覆蓋OnException處理程序
public abstract class MyBaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
// add my own status code
Response.StatusCode = 550;
// write the error message to the response
Response.Write(filterContext.Exception.Message);
// mark the exception as handled
filterContext.ExceptionHandled = true;
}
base.OnException(filterContext);
}
}
在對文件準備好客戶端註冊我全球處理器適合於Ajax錯誤
$(document).ready(function(){
$.ajaxSetup({
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==550){ // <----- THIS IS MY CUSTOM ERROR CODE --------
alert(x.responseText);
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
});
當然你也可以調整這個方法適合您的需求。希望這可以幫助。
你的意思是驗證錯誤?或錯誤狀態代碼的迴應?或者是什麼? –
@Michael Sagalovich JavaScript錯誤事件處理程序用服務器的錯誤消息調用,我想向用戶顯示此錯誤消息。 – aknuds1