by Mikael Henriksson
8. September 2010 22:09
First of all I want to direct you to one of the best blog posts ever. I could be giving away free points because it saved my soft behind from getting whipped but really guys, after searching high and low for some time and ending up with nothing I was finally able to do remote validation with jQuery and MVC!
Actually I have been able to do remote validation before but not using MicrosoftMVCJQueryValidation.js at the same time. Problem is that MMVCJQV overwrites the rules with some metadata somehow (not sure how but I’m working on it). So adding a remote rule at document.ready does nothing because MMVCJQV will just wipe it.
There was a tiny problem with his code though. I could not get it to work with more than one additionalProperty so I modified it a little. His method would never return more than the first additionalProperty so Invoice_Id would be the value for a date etc .
I changed the following code:
if (props) {
var data = {};
for (var i = 0, l = props.length; i < l; ++i) {
var param = props[i];
data[props[i]] = function () {
return $("#" + param).val();
}
}
obj["data"] = data;
}
Into this :
if (props) {
var data = {};
for (var i = 0; i < props.length; i++) {
var param = props[i];
data[props[i]] = $("#" + param).val();
}
obj["data"] = data;
}
Edit:
Forgot to mention how I handle this on server side. I just use a FormCollection
[HandleError]
[HttpPost]
public virtual ActionResult DayIsValid(FormCollection form)
{
var day = short.Parse(form["Day"]);
var invoiceId = int.Parse(form["Invoice_Id"]);
var result = _repository.DayIsUniqueForInvoice(invoiceId, day);
var startDate = DateTime.Parse(form["Invoice_StartDate"]);
DateTime dtTo = startDate;
// overshoot the date by a month
dtTo = dtTo.AddMonths(1);
dtTo = dtTo.AddDays(-(dtTo.Day));
return Json(result && dtTo.Day >= day);
}
Keep in mind folks that it’s the generated id for the property that it will look for not the property name! Very important if you have complex models.´
Thanks again to Richard Kimber
f70c581d-93f3-48ba-97e0-c41e6234b648|0|.0
Tags: