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. Web 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 コントローラー:

    public DataCollection GetSomeData() { var data = GetData(); if( data == null ){ throw new Exception("Data is null");

    }

  2. 以下のようなビューモデルを作成しました。

    var vm = { activate: activate, getDataSuccess: ko.observableArray(), errorMessage:ko.observable(), title: 'TopNews' };

  3. divの1つのビューページにバインドします

    -- <-div class="error" data-bind="text: errorMessage" />

    上記の方法が正しいかどうかはわかりません。しかし、私はこのようにする必要があります。

4

4 に答える 4

1

サーバー側のコードでは、例外を HttpResponseException にラップする必要があります。

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

通常、このメッセージ.ajaxErrorは jquery のハンドラーでキャッチできます。

または、より洗練されたカスタム 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));
            });
        }
    }
};

そして、このバインディングへのデータ バインドを使用して、HTML のどこかに DIV を追加するだけです。

于 2013-04-29T12:05:23.977 に答える
0

success および error パラメータ ( doc ) を使用する必要があります。

このようなことを試してください。

$.ajax({
    type: "GET",
    url: "error.com", // your url
    error: function (jqXHR, textStatus, errorThrown) {
        vm.response('Error ' + errorThrown)
    },
    success: function (respo) {
        vm.response("Success" + response)
    }
})
于 2013-04-29T12:26:47.127 に答える
0

私の経験では、これをシームレスに処理する最善の方法は、予期しないエラーを処理しないように Web API を設定することです。これにより、次のように Web API コードが非常にクリーンでシンプルになります。

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

なんらかの理由でカスタム例外をスローしたい場合 (データが null の場合に表示する特定のメッセージがある場合など) は、通常どおり例外をスローできます。

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() も使用できます)。

この決定に役立つかもしれないスタック オーバーフローに関する別の質問があります: ノックアウト js ベスト プラクティス ajax エラー処理

于 2013-04-29T12:39:51.680 に答える
0

ビューに戻るモデルに追加する必要があります。あなたのビューモデル。

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

        });
于 2013-04-29T11:58:45.507 に答える