I have only just started using MVC and jQuery validate so please bear with me. I also have no idea what the title of my question should be. 8(
Overview
I am using MVC 4 with jQuery validate. My form is being validated on the client side. I have a scenario where two very alike objects need to be on my form. This has been achieved by means of a ModelView which has two properties. The ModelView is linked to the View and everything works excepting the remote validation. I need to validate a field based on a particular value in the object. Everything is linked together nicely excepting the parameters of the validation action in the controller. Before you give me disapproving tsk tsks, I made up the following code scenario.
The Code
Model class where Name
requires remote validation depending on the value of GroupID
. Essentially, the name is unique to the group.
public class Colour
{
[Key]
public int GroupID {get;set;}
[Required]
[Remote("ColourExists", "Validation", AdditionalFields = "GroupID")]
public string Name {get;set;}
}
Validation controller where the ColourExists
action resides.
public class ValidationController :Controller {
public JsonResult ColourExists(string name, string groupID) {
// Add validation here later
return Json(false, JsonRequestBehavior.AllowGet);
}
}
The View and Controller is linked to a ModelView so that I can display two separate instances on my form. Typically I need to ask the user for a Bright and a Dark colour for one group. (Before you tsk, remember, this isn't for real)
public class ColourViewModel {
public Models.Colour BrightColour { get; set; }
public Models.Colour DarkColour {get;set;}
}
The generated HTML has input fields BrightColour_Name
and DarkColour_Name
. These fields have data-val-remote-additionalfields=*.Name
attributes. On blur they GET
the correct action and controller but the parameters are null. The expected parameters are InstanceName.VariableName
such as BrightColour.Name
and DarkColour.Name
. The request is sent as follows Validation/ColourExists?BrightColour.Name=red&BrightColour.GroupID=10
So how should I pass the values through to the ColourExists
action in the validation Controller if my values are linked to variables of an instance?
Edit
The view looks as follows:
@model Colours.ViewModels.ColourViewModel
@using (Html.BeginForm()) {
@Html.LabelFor(model => model.DarkColour.Name)
@Html.EditorFor(model => model.DarkColour.Name)
@Html.HiddenFor(model => model.DarkColour.GroupID)
<input type="submit" value="Save" />
}