Remote Validation on Datagrids

May 16, 2013 at 6:22 AM
Edited May 16, 2013 at 6:23 AM
Hi There,

I'm having trouble with Remote client side validation of items in a datagrid. From what I can see Remote validation requires the property name on the ViewModel object and Form to be exactly the same as the parameter name in the Controller Action method.

In a datagrid this is not possible as each property name takes on a MVCControlsToolkit suffix.
How do I make the Remote validation work?

In my example below the AjaxValidatePortfolioExists method is actually called but the Portfolio parameter is null, presumably because the actual property on the form is PortfolioAllocations___0___Item_Value_Portfolio
E.g. Class
public class ViewModel.PortfolioAllocation {
   [Remote("AjaxValidatePortfolioExists", "Portfolio")]
   public string Portfolio {get;set;}
}
Controller Action method:
[ActionAuthorise(Process = "GetPortfolio")]
[HttpGet, System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult AjaxValidatePortfolioExists(string Portfolio)
{
    return Json(Portfolio=="abc", JsonRequestBehavior.AllowGet);
}
Coordinator
May 17, 2013 at 7:21 AM
It is a sell known problem. The remote attribute doesnt work with items from a list, exactly because the parameter inserted in the query string contains a prefix that depends on the position of the item in the list. In theory, one might think to define a custom model binder that doesn't consider this prefix, but what a similar model binder should do depend strongly on the specific situation(there might be nested objects, or nested lists), so it is difficult to provide an out-of-the-box solution.
The only "acceptable" way is using a dirty trick!

Solution:

Just take the value of the parameter from the Asp.net Request object. The Request object contains a dictionary with all parameters passed in the query string. Look for a key that ends with ".Portfolio" , and take the corresponding value.
May 19, 2013 at 8:18 AM
Thanks for the response, I suspected as much. I have hacked the validation into a javascript function used to get some other information for the portfolio, so the error is now shown, although it doesn't use the built in validation. I'll give your solution a go next time I get the chance.