2013-04-29 26 views
0

我正在調用服務器的ajax請求一些數據。例如:http/get(SomeDataService)。 在控制器我有數據對象如下:如何在挖空視圖模型中綁定服務器端異常?

API控制器:

public DataCollection getSomeData() 
{ 
try{ 
// get the data in object and checking its null or not. 
//If not null, will bind the data in ko viewModel.if null throw below exception. 
} 
catch(Exception e) 
{ 
e. message(" No Data Found") 
} 
} 

現在我想結合KO視圖模型和視圖內的「未找到數據」消息。

請問我該怎麼做?我是新來的KO,ASP.net

我再次重新發布我實際需要的東西。 1.一種製造幅材的API調用Ajax

function GetData() { 

      var data = http.get(apiUrl) 
      .success(function (data) { 
       if (data != null) 
       { 
        // some stuff for success data 

        vm.getDataSuccess; 
       } 
       else { 
        vm.errorMessage();// server side exception message. 

      }) 
  1. 的WebAPI控制器:

    公共數據收集GetSomeData() { VAR數據=的GetData(); (data == null){ throw new exception(「Data is null」);

    }

  2. 我已創建視圖模型象下面這樣:

    變種VM = { 激活:激活, getDataSuccess:ko.observableArray(), 的errorMessage:ko.observable(), 標題:'TopNews' };

  3. 在div

    之一視圖頁上綁定 - < -div類= 「錯誤」 數據綁定= 「文本:的errorMessage」/>

    我不知道上述的方法是正確與否。但我需要這樣。

回答

0

你必須將它添加到模型youre返回到視圖ie。你的viewmodel。

,如果你使用的AJAX,那麼你拋出該異常會被返回到AJAX功能 電話:

$.ajax({ 
      type: "POST", 
      url: "/chart/setfilter", 
      data: JSON.stringify(filters), 
      dataType: "json", 
      contentType: "application/json; charset=utf-8" 
     }).done(function (res, status, xhr) { 
      //here res will contain the exception 

     }); 
+0

如何獲得在視圖模型錯誤消息? – user2706 2013-04-29 12:00:43

1

在您的服務器端代碼,您應該穿得異常到HttpResponseException:

try 
{ 
    // ... your stuff here 
} 
catch (Exception exception) 
{ 
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) 
    { 
     ReasonPhrase = exception.Message 
    }); 
} 

你一般可以在jQuery的.ajaxError處理程序上捕獲這條消息。

或者更炫,創建自定義KO結合:

ko.bindingHandlers.flash = { 
    prepareInfo: function (valueAccessor) { 
     var info = {}, 
      options = ko.utils.unwrapObservable(valueAccessor()); 

     if (options && options.value) { 
      info.value = options.value; 
     } else { 
      info.value = valueAccessor(); 
     } 

     return info; 
    }, 
    init: function (element, valueAccessor) { 
     var info = ko.bindingHandlers.flash.prepareInfo(valueAccessor); 

     $(element) 
      .ajaxError(function (event, xhr, ajaxSettings, errorThrown) { 
       info.value(errorThrown); 
      }).ajaxSend(function() { 
       info.value(null); 
      }); 

     $(element).hide(); 
    }, 
    update: function (element, valueAccessor) { 
     var info = ko.bindingHandlers.flash.prepareInfo(valueAccessor); 
     if (info.value()) { 
      $(element).stop().hide().text(info.value()).fadeIn(function() { 
       clearTimeout($(element).data("timeout")); 
       $(element).data("timeout", setTimeout(function() { 
        $(element).fadeOut('fast'); 
        info.value(null); 
       }, 3000)); 
      }); 
     } 
    } 
}; 

然後只需用數據綁定添加一個DIV的地方在HTML此綁定。

+0

這個自定義綁定是做什麼的?你可以在jsfiddle plz上演示嗎? – Xerxes 2013-04-29 12:11:52

+0

我無法找到一種模擬HTTP 500錯誤代碼的方法,但實際上我已經將這個東西放在了一起。 http://jsfiddle.net/Pm4xS/ – gnz 2013-04-29 12:57:48

+0

哦,非常好,謝謝 – Xerxes 2013-04-29 13:25:05

0

您應該使用成功和錯誤參數(doc)。

嘗試類似this

$.ajax({ 
    type: "GET", 
    url: "error.com", // your url 
    error: function (jqXHR, textStatus, errorThrown) { 
     vm.response('Error ' + errorThrown) 
    }, 
    success: function (respo) { 
     vm.response("Success" + response) 
    } 
}) 
0

根據我的經驗,處理這種無縫的最佳方法是設置您的web api,以便它不負責處理意外錯誤。這樣可以使網頁API代碼非常乾淨和簡單,像這樣:

public DataCollection GetSomeData() 
{ 
    var data = GetData(); 
    return data; 
} 

如果您想扔無論出於何種原因自定義異常 - 也許你有一個特定的消息顯示,如果數據爲空 - 你可以拋出一般異常:

public DataCollection GetSomeData() 
{ 
    var data = GetData(); 
    if(data == null){ 
     throw new Exception("Data is null"); 
     //or... throw new MyCustomException("Data is null"); 
    } 
} 

現在,到目前爲止,這種做法是不能接受的,因爲它可能暴露敏感信息的服務器到客戶端。爲了清楚地處理這個問題,創建一個處理異常的自定義操作過濾器。例如:

/// <summary> 
/// Represents an attribute that will automatically process any unhandled exceptions 
/// that occur during during the execution of a web api action 
/// </summary> 
public class HandleExceptionAttribute : ExceptionFilterAttribute 
{ 
    public override void OnException(HttpActionExecutedContext actionExecutedContext) 
    { 
     //log the error (make sure LogError doesn't throw any exceptions) 
     LogError(actionExecutedContext); 

     //set up a default message that is safe to send to the client 
     // (doesn't expose any sensitive exception information) 
     var message = "An error has occured please try your request again later"; 

     //if the exception is, or inherits from MyCustomException, then 
     // go ahead and forward the message on the client 
     if (actionExecutedContext.Exception is MyCustomException) 
     { 
      message = actionExecutedContext.Exception.Message; 
     } 

     actionExecutedContext.Response = 
      actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, message); 
    } 
} 

請務必在全局應用此操作篩選器,以便它適用於所有Web API方法,而無需任何開發人員干預。這樣,您可以確信沒有未處理的異常將原始異常消息返回給客戶端。


現在,你有錯誤,從服務器回來正常,您可以通過多種方式顯示信息給用戶。要做的最簡單的事情就是立即顯示消息,而不是嘗試將其添加到視圖模型。您可以使用toast.js或其他通知機制(甚至是window.alert())向用戶顯示一條消息,直到您走得更遠。

這裏的堆棧溢出的另一個問題,可能與此決定幫助:knockout js best practices ajax error handling

相關問題