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