简体   繁体   中英

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

If my server side validation passes I want to show a message that I pass back from the server to the client. Error messages are possible (defined as an attribute on the property in ASP.Net MVC), can I show a success message? Maybe I can tap into the JQuery validate plugin to do this??

ex. I do a lookup from of the location to get a city I want to pass back the city as a string to display it as a validation success message.

Here is my code.

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

EDIT here is what I tried. I'm using jQuery Validate now instead of remote attributes on my c# property. This works fine but how do I define a success property here in remote and pass that success message to the validation messsage? and then change the color to green instead of red?

$('#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();
      }
    }
  }
});

EDIT 2 I really want to show a succes message coming from the server (ex. shoing the city when a zip is entered), so I think I can use a success callback on the remote call and in the callback manipulate the message color and make the element valid. I think validate sets it to false if there is a string in the JSon response?

something like this.

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

The success option of the .validate() method is used for controlling the message element when validation passes. By default, the error message is hidden when validation passes. When using success , you can modify this behavior and show an icon, message, etc. when validation passes. However, this option does not retrieve messages from your server.

jQuery Validate is client-side code, and there is only one built-in method that will take a response from the server and that is the remote method. However, the issue here is that you can only pass a true to pass validation, a false to fail validation... and if you pass a string, it's converted into an error message and validation fails .

AFAIK, there is no built-in method for doing what you want . Perhaps you can write a custom success function that uses .ajax() to retrieve a message from your server.


Summary :

  1. the plugin does not typically show messages on success. The success option is a way to force it to show messages. However, the issue with this is that you cannot pass a value into this option. It's just a way to control the error message object when the field is valid.

  2. the plugin does not typically communicate with the server except for the remote method. The issue with this is that you can only pass true to pass validation. If you pass a string, validation will fail ( and the string becomes the validation error message ).


EDIT in response to OP:

but how do I define a success property here in remote and pass that success message to the validation messsage?

You can only use the success option to properly manipulate the error element . However, I don't think you'll be able to achieve the stated objective since there does not seem to be a way to pass the field's value into the success option. Otherwise, you could use .ajax() within success to retrieve your message.

and then change the color to green instead of red?

This is done automatically by defining your CSS properties for the valid and error classes. You can also apply custom classes using .addClass() within the success option.

IMO, your entire goal cannot be achieved using the jQuery Validate plugin. However, you should thoroughly review the documentation to be sure for yourself.


I think validate sets it to false if there is a string in the JSon response?

Yes, exactly as already stated in my answer. If the server response is anything other than true , the validation is set to fail.

What you can do is this

Use ajax to call a custom action method instead of remote data annotation

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

I wish code below helps you.

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

Now as Sparky has mentioned in message above give call to your action or method using ajax and write a custom success function

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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