繁体   English   中英

在 ASP.Net MVC 中显示来自服务器端验证的成功验证消息

[英]Showing a success validation message in ASP.Net MVC from server side validation

如果我的服务器端验证通过,我想显示一条从服务器传回客户端的消息。 可能会出现错误消息(在 ASP.Net MVC 中定义为属性上的属性),我可以显示成功消息吗? 也许我可以利用 JQuery 验证插件来做到这一点?

前任。 我从该位置进行查找以获取我想将城市作为字符串传回以将其显示为验证成功消息的城市。

这是我的代码。

    [Required()]
    [MaxLength(5)]
    [MinLength(5, ErrorMessage = "Can't find location")]
    [Display(Name = "Zip code")]
    [Remote("CheckLocation", "Account", AreaReference.UseCurrent, ErrorMessage = "Invalid zipcode")]
    public string Location { get; set; }


    [HttpGet]
    [AllowAnonymous]
    public JsonResult CheckLocation(int Location)
    {
        var city = getLocation(Location);
        if (city != null)
        {
            // pass the city back with the JSon object, but how do I display it???
            return Json(true, JsonRequestBehavior.AllowGet);
        }
        return Json(false, JsonRequestBehavior.AllowGet);
    }

编辑这里是我试过的。 我现在使用 jQuery Validate 而不是我的c#属性上的远程属性。 这工作正常,但如何在远程定义成功属性并将该成功消息传递给验证消息? 然后将颜色更改为绿色而不是红色?

$('#Location').rules("add", {
  required: true,
  minlength: 5,
  maxlength: 5,
  messages: {
    required: "Required input",
    minlength: jQuery.validator.format("Please, {0} characters are necessary"),
    maxlength: jQuery.validator.format("Please, {0} characters are necessary")
  },
  remote: {
    url: "CheckLocation",
    type: "post",
    data: {
      Location: function() {
        return $('#Location').val();
      }
    }
  }
});

编辑 2我真的想显示来自服务器的成功消息(例如,在输入 zip 时向城市发送消息),所以我想我可以在远程调用中使用成功回调,并在回调中操作消息颜色并制作元素有效。 我认为如果 JSon 响应中有字符串,validate 会将其设置为 false?

像这样的东西。

        [HttpGet]
    [AllowAnonymous]
    public JsonResult CheckLocation(int Location)
    {
        var city = getLocation(Location);
        if (city != null)
        {
            return Json(city); // this will be text like "London"
        }
        return Json(false);
    }
$('#Location').rules("add", {
  required: true,
  //minlength: 5,
  maxlength: 5,
  messages: {
    required: "Required input",
    minlength: jQuery.validator.format("Please, {0} characters are necessary"),
    maxlength: jQuery.validator.format("Please, {0} characters are necessary")
  },
  remote: {
    url: "CheckLocation",
    type: "post",
    data: {
      Location: function() {
        return $('#Location').val();
      }
    },
    success: function(data) {
      // change the color from red to green for the message
      // make the invalid element valid so it passes submition
    }
  }
});

.validate()方法success选项用于在验证通过时控制消息元素。 默认情况下,验证通过时隐藏错误消息。 使用success ,您可以修改此行为并在验证通过时显示图标、消息等。 但是,此选项不会从您的服务器检索消息。

jQuery Validate 是客户端代码,只有一种内置方法会从服务器获取响应,那就是remote方法。 但是,这里的问题是您只能传递true以通过验证,传递false以失败验证……如果您传递一个字符串,它会转换为错误消息并且验证失败

AFAIK,没有内置的方法可以做你想做的事 也许您可以编写一个自定义success函数,使用.ajax()从您的服务器检索消息。


总结

  1. 该插件通常不会显示成功消息。 success选项是一种强制它显示消息的方法。 但是,问题在于您无法将值传递给此选项。 这只是在字段有效时控制错误消息对象的一种方式。

  2. 除了remote方法,插件通常不与服务器通信。 这样做的问题是您只能通过true来通过验证。 如果您传递一个字符串,验证将失败(并且该字符串成为验证错误消息)。


编辑以回应 OP:

但是如何在远程定义成功属性并将该成功消息传递给验证消息?

您只能使用success选项来正确操作错误元素 但是,我认为您无法实现既定目标,因为似乎没有办法将字段的值传递给success选项。 否则,您可以success地使用.ajax()来检索您的消息。

然后将颜色更改为绿色而不是红色?

这是通过为validerror类定义 CSS 属性来自动完成的。 您还可以在success选项中使用.addClass()应用自定义类。

IMO,使用 jQuery Validate 插件无法实现您的整个目标。 但是,您应该彻底查看文档以确保自己。


我认为如果 JSon 响应中有字符串,validate 会将其设置为 false?

是的,正如我在回答中所说的那样。 如果服务器的响应比其他任何true的验证是一套失败。

你能做的是这个

使用ajax调用自定义action方法代替远程数据注解

    var url = "/MyController/CheckLocation/";

$.ajax({
    url: url,
    data: { zipcode: _zipcode },
    cache: false,
    type: "POST",
    dataType: "json"
}).done(function (obgcity) {

     //If objcity is null then display error else display city
    }
});

我希望下面的代码可以帮助你。

public ActionResult CheckLocation(int Location)
    {
        var city = getLocation(Location);
        if (city != null)
        {
            // city is string type, example: string city="Mumbai";
            return Json(new {Status=true, City = city}, JsonRequestBehavior.AllowGet);
        }
        return Json(new { Status=false, City=""}, JsonRequestBehavior.AllowGet);
    }

现在,正如 Sparky 在上面的消息中提到的,使用 ajax 调用您的操作或方法并编写自定义成功函数

 var locationId = 20;
 $.ajax({
    url: "MyController/CheckLocation",
    data: { Location: locationId},
    cache: false,
    type: "GET",
    dataType: "json",
    success: function (data) {
             if(data.Status == true)
             {
                 alert(data.City); 
                // instead of alert you can create custom message alert box,
                // or if you want to display city name or whatever message
                // you can try $("#cityId").Html("<p>this is city</p>");   
             }        
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert("Ajax Failed!!!");
     }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM