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 viewModel 和视图中绑定“未找到数据”消息。

请建议我如何做到这一点?我是 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 控制器:

    公共 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 中的视图页面上绑定

    -- <-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
    });
}

您通常可以在.ajaxErrorjquery 的处理程序上捕获此消息。

甚至更高级,创建自定义 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

In my experience, the best way to handle this seamlessly is to set up your web api so that it is not responsible for handling unanticipated errors. This keeps the web api code very clean and simple, like this:

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

If you'd like to throw a custom exception for whatever reason - maybe you have a specific message to display if the data is null - you can throw the exception normally:

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

Now, so far this approach is not acceptable, because it can potentially expose sensitive server information to the client. In order to handle this cleanly, create a custom action filter that handles the exceptions. Something like this:

/// <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);
    }
}

Be sure to apply this action filter globally, so that it applies to all web api methods without any developer intervention. That way you can be confident that no unhandled exceptions are throwing raw exception messages back to the client.


Now that you have the error coming back from the server properly, you can display the message to your users in a number of ways. The cleanest thing to do is to simply display the message immediately and not try to add it to the view model. You can display a message to the user using toast.js or some other notification mechanism (even window.alert() until you get further down the road).

Here's another question on Stack Overflow that may help with this decision: knockout js best practices ajax error handling

于 2013-04-29T12:39:51.680 回答
0

您应该使用成功和错误参数(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

您必须将其添加到您要返回视图的模型中,即。你的视图模型。

如果您使用的是 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 回答