【问题标题】:How to show server side validation error in MVC view page while calling the action method using Ajax使用 Ajax 调用操作方法时如何在 MVC 视图页面中显示服务器端验证错误
【发布时间】:2013-08-03 09:43:57
【问题描述】:

我是 MVC 淘汰赛的新手,谁能帮帮我。

我正在使用淘汰赛 js 在 ajax 调用中调用 MVC4 webapi 操作方法。 当我单击登录按钮时,它会调用 WebApi Action 方法。让我们考虑一下,当我如何在视图中显示错误消息时,用户 ID 和密码无效。

var User = function () {
    this.Email = ko.observable();
    this.Password = ko.observable();
};


var LoginViewModel = function () {
    var self = this;
    this.IncorrectLogin = ko.observable(false);

    this.User = ko.observable(new User());
    this.Login = function () {
        $.ajax({
            url: '../api/Login/PostAddUser',
            contentType: "application/json",
            cache: false,
            dataType: 'json',
            type: 'POST',
            data: "{'Email':'" + self.User.Email + "' , 'password':'" + self.User.Password + "'}",
            success: function (data,status,xhttps) {
                var result = data;
                if (data == true) {
                    window.location.href = '../User/Account';
                } else {

                }
            },
            error: function (data, status, xhttps) {
                alert('failed');
            }
        });
    };

};
ko.applyBindings(new LoginViewModel());

因此,如果该用户名和密码无效,我想在视图中显示一些消息。 如何将错误消息从控制器传递到视图?

 public bool PostAddUser(User user)
        {
            User u = DataAccessLayer.ValidateUser(User.email, User.password);
            if (string.IsNullOrEmpty(u.Id) || u.Id == 0)
            {
                //retun the custome validation error like Invalid UserId
            }
            else
            {
                if (u.activeCodeConfirmed)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

【问题讨论】:

    标签: jquery asp.net-mvc-4 knockout.js asp.net-web-api


    【解决方案1】:

    使用jquery发送消息给

    <span id="messageError" style="display:none; color:red"> </span> 
    

    这将在输入登录并通过。

    if (data == true) {
                        window.location.href = '../User/Account';
                    } else {
                        $('span#messageError').text('user and password is not valid');
                        $('span#messageError').css('display','inline');
                    }
    

    稍后输入用户名或密码,您可以执行 onclick = "hideMessage()" 隐藏

    function hideMessage ()
    {
    $('span#messageError').css('display','none');
    }
    

    【讨论】:

      【解决方案2】:

      从您的代码看来,您已经设置了以下内容:

      1. this.IncorrectLogin = ko.observable(false);
      2. if (data == true) { window.location.href = '../User/Account'; } else { \\Do something }

      首先,最好将模型的 this 绑定到一个变量中,这样您就不会混淆在回调中遇到的所有 this。

      因此,您可以执行以下操作:

      var self = this;
      self.IncorrectLogin = ko.observable(false);
      //... other code
      

      所以在你的 AJAX 回调中,如果登录为 false,你可以更新这个 observable,像这样:

      if (data == true) { 
          window.location.href = '../User/Account'; 
      } else { 
          self.IncorrectLogin(true); 
      }
      

      既然您有办法将这个错误登录通知 KO,您可以选择在 HTML 表单中显示错误消息或其他内容。示例:

      <div data-bind="visible: IncorrectLogin">
          <span style="color: red">I will only show up if it's an incorrect login!</span>
      </div>
      

      这就是您如何使用 KO 查看更新的基础知识。

      现在,如果您有来自服务器的错误消息,比如data.message,那么您只需采用相同的概念并使消息可观察。有点像:

      self.ErrorMessage = ko.observable('');
      
      //AJAX callback
      if (data.valid) { 
          window.location.href = '../User/Account'; 
      } else { 
          self.ErrorMessage(data.message); 
      }
      

      在您的 HTML 中,

      <div data-bind="visible: ErrorMessage() != ''">
          <span style="color: red" data-bind="text: ErrorMessage"></span>
      </div>
      

      请注意,KO observables 是函数,但如果 observable 不是表达式的一部分,则不需要使用 () 表示法。参见visible: ErrorMessage() != '' 与text: ErrorMessage。

      干杯:)

      【讨论】:

      • 嗨 Jensen Ching,我怎样才能在 ajax 成功方法中获取服务器端错误?让我们考虑用户 ID 不存在我想显示消息,如用户 ID 不存在,在某些情况下,我想显示密码错误。
      • 我已经更新了我的答案。基本上,您只需要在从服务器传递到客户端的 JSON 结果中传递错误消息。比如data.message。
      • 基本上@jensen chang 我还有其他条件我正在根据该条件检查我是否返回真/假(如果用户存在)但如果用户不存在我想返回一些自定义错误消息控制器查看希望你理解我的问题:)
      • 你必须在服务器端弄清楚,因为我不熟悉 .NET MVC,但它的要点是:现在,你的“数据”来自服务器只是一个布尔值。如果您想返回一个字符串,请将此结果设为一个对象,其中包含名为valid 和message 的属性。然后在服务器端,在验证失败后,填充这个对象,例如`valid=false, message="Custom message",然后把这个结果传回给客户端。之后,我提供的代码可以帮助您显示自定义错误消息。
      • 如果您的问题更多地针对服务器端,我建议您编辑您的问题,因为目前,它似乎专注于客户端问题,因此您将不断获得客户端响应.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      相关资源
      最近更新 更多