2011-09-02 32 views
4

我通過JavaScript處理程序(我使用jQuery)將表單提交給ASP.NET MVC 3服務器,並從另一個JavaScript處理程序中的服務器接收錯誤響應。我想知道的是,我應該如何在視圖中顯示來自表單提交的錯誤消息?我寧願使用一些標準的ASP.NET MVC 3 idiom /構造。什麼是在ASP.NET MVC 3視圖中顯示來自JavaScript(jQuery)的錯誤的推薦方式?

編輯

注意,我想從服務器顯示錯誤消息,在JavaScript錯誤處理功能接收。

+0

你的意思是驗證錯誤?或錯誤狀態代碼的迴應?或者是什麼? –

+0

@Michael Sagalovich JavaScript錯誤事件處理程序用服務器的錯誤消息調用,我想向用戶顯示此錯誤消息。 – aknuds1

回答

2

你可以去純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>'); 
}); 
+0

我已經進行了客戶端驗證。我問的是如何顯示我*從服務器*收到的錯誤。 – aknuds1

+0

那麼在JS和服務器之間沒有任何自定義消息傳遞的內置構造。你只需要創建一個div(例如用「錯誤」的ID或類似的東西),然後手動在那裏寫消息。 –

+0

我想錯誤創建是有趣的一點。也許有一些jQuery API用於創建適當樣式的錯誤div? – aknuds1

1

假設你正在使用jQuery的驗證帶有MVC解決方案模板,在你的JavaScript處理程序,你將不得不錯誤添加到驗證。有一個showErrorsmethod 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對象。我在服務器端建立了幾個ControllerViewModel擴展來實現這一點。

在服務器端

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 
} 
+0

請您詳細說明我應該如何從JavaScript函數生成驗證摘要? – aknuds1

+0

$(this).data('validator')對我來說是未定義的,即使包含jquery.validate.min.js也是如此。 – aknuds1

+0

'$(this)'在我的例子中是指形式。如果表單已經被jQuery驗證,它將會有一個數據('validator')實例。在你的情況下,只需嘗試'$('#form-id-here')' –

1

服務器應具有標準化的消息作出響應。該消息可能包含一個完整的錯誤消息(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更好地工作。但是,它不允許使用帶格式的錯誤消息(例如,使用鏈接等)

1

我在過去回答了類似的問題,用於添加錯誤消息。

MVC Validation Summary manipulation with JS and Dynamic DOM elements

既然你要什麼我假設是你已經知道JavaScript方法從服務器回來的錯誤,只需添加

 

var ul = $("#validationSummary ul"); ul.append("<li>Custom Error Message</li>") 
 
+0

看起來很有趣,我會在工作時檢查一下在星期一。 – aknuds1

+0

#validationSummary顯然不是由MVC渲染的,可能是因爲沒有任何MVC已知的錯誤。 – aknuds1

0

我做到這一點的方法是:

創建基本控制器類並覆蓋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); 
     } 
    } 
}); 
}); 

當然你也可以調整這個方法適合您的需求。希望這可以幫助。

+0

OP是收到表單提交錯誤,通常是狀態碼200,帶有一些消息,而不是500例外。在這種情況下,200個結果不會是ajax錯誤。 –

+0

錯誤接收不是問題的一部分,因爲我已經有一個回調從服務器接收錯誤消息,問題只是顯示消息。我不確定是否要顯示一個消息框(警報)。 – aknuds1

+0

Adam Tuliper - 錯誤應該與狀態碼200不同,應該(通常)在集中的功能中處理(更好的代碼可維護性)。代碼200應該調用特定的成功處理程序,而返回不同於200的狀態代碼意味着有問題,應該以不同的方式處理 – shizik

相關問題