Knockout.js 如何在淘汰视图模型中绑定服务器端异常?

Knockout.js 如何在淘汰视图模型中绑定服务器端异常?,knockout.js,Knockout.js,我正在对服务器进行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 exc

我正在对服务器进行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和view中绑定“未找到数据”消息

请告诉我怎么做?我是新来的,ASP.net

我正在重新发布我真正需要的东西。 1.实现webapi的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.

            })
  • WebApi控制器:

    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")
    }
    }
    
    公共数据收集GetSomeData() { var data=GetData(); 如果(数据==null){ 抛出新异常(“数据为空”)

    }

  • 我创建了viewmodel,如下所示:

    var vm={ 激活:激活, GetDataSucces:ko.observableArray(), errorMessage:ko.observable(), 标题:“热门新闻” })

  • 在其中一个div中的视图页上绑定

    --

    我不确定上述方法是否正确。但我需要这样的方法


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

    如果您使用的是ajax,那么抛出的异常将返回到ajax函数 电话:


    在服务器端代码中,应将异常包装为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));
                });
            }
        }
    };
    

    然后在HTML中的某个地方添加一个DIV,并将数据绑定到此绑定。

    您应该使用success和error参数()

    试试类似的东西


    根据我的经验,无缝处理此问题的最佳方法是设置web api,使其不负责处理意外错误。这使web api代码非常干净和简单,如下所示:

    public DataCollection GetSomeData()
    {
        var data = GetData();
        return data;
    }
    
    /// <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);
        }
    }
    
    如果出于任何原因希望引发自定义异常(如果数据为空,可能会显示特定消息),则可以正常引发异常:

    public DataCollection GetSomeData()
    {
        var data = GetData();
        if( data == null ){
            throw new Exception("Data is null");
            //or... throw new MyCustomException("Data is null");  
        }
    }
    
    现在,到目前为止,这种方法是不可接受的,因为它可能会向客户端公开敏感的服务器信息。为了干净地处理这种情况,请创建一个处理异常的自定义操作筛选器。如下所示:

    public DataCollection GetSomeData()
    {
        var data = GetData();
        return data;
    }
    
    /// <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操作期间发生的错误
    /// 
    公共类HandleExceptionAttribute:ExceptionFilterAttribute
    {
    public override void OneException(HttpActionExecuteContext ActionExecuteContext)
    {
    //记录错误(确保LogError不会引发任何异常)
    日志错误(actionExecutedContext);
    //设置可安全发送到客户端的默认消息
    //(不公开任何敏感的异常信息)
    var message=“发生错误,请稍后重试您的请求”;
    //如果异常是或继承自MyCustomException,则
    //继续并转发客户端上的消息
    如果(ActionExecuteContext.Exception是MyCustomException)
    {
    message=ActionExecuteContext.Exception.message;
    }
    ActionExecuteContext.Response=
    ActionExecuteContext.Request.CreateResponse(HttpStatusCode.InternalServerError,消息);
    }
    }
    
    请确保全局应用此操作筛选器,以便它在没有任何开发人员干预的情况下应用于所有web api方法。这样,您就可以确信没有未处理的异常将原始异常消息发回客户端


    现在服务器正确返回错误,您可以通过多种方式向用户显示消息。最简单的方法是立即显示消息,而不是尝试将其添加到视图模型中。您可以使用toast.js或其他通知机制向用户显示消息(即使是window.alert(),直到你走得更远)


    这里还有一个关于堆栈溢出的问题,可能有助于做出这个决定:

    这个自定义绑定做什么?你能在JSFIDLE plz上演示一下吗?我找不到一种方法来模拟HTTP 500错误代码,实际上会触发这个错误,但我已经用这个东西编写了一个简单的JSFIDLE。