Remote validation attribute in MVC3 invalid get format
-
05-07-2021 - |
Question
I trying to use remote validation for the first time, but am encountering problems with the parameters passed inot the remote validation method.
My model is as follows:
public class PerinatalWomanView : IPerinatalWoman
{
[Required(ErrorMessage = "The woman's postcode is required")]
[Display(Name = "Woman's postcode")]
[Remote("PostcodeCheck", "Validation", "Validation")]
[RegularExpression("^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} [0-9][A-Za-z]{2}$", ErrorMessage = "A valid postcode is required")]
public string Postcode { get; set; }
The view snippet is:
<div class="editor-label control-label">
@Html.LabelFor(m => m.perinatalWomanView.Postcode)
</div>
div class="editor-field controls">
@Html.EditorFor(m => m.perinatalWomanView.Postcode)
@Html.ValidationMessageFor(m => m.perinatalWomanView.Postcode)
</div>
and the validation controller is:
public class ValidationController : Controller
{
//
// GET: /Validation/Validation/
[HttpGet]
public JsonResult PostcodeCheck(string Postcode)
{
// postcode has already been checked for correct format
// now look it up to see if it exists
string mbrraceCommonCodeEntitiesConnectionString = ConfigurationManager.ConnectionStrings["MbrraceCommonCodeEntities"].ConnectionString;
if (PostcodeChecks.CheckPostcodeExists(mbrraceCommonCodeEntitiesConnectionString, Postcode))
{ return Json(true, JsonRequestBehavior.AllowGet); }
return Json("This postcode was not found in the database", JsonRequestBehavior.AllowGet);
}
When the controller is called the value of Postcode is null. The actual call - from Firebug - is:
http://localhost:57881/Validation/Validation /PostcodeCheck?perinatalWomanView.Postcode=OX4+1SU
How do I read the postcode string parameter correctly becuase it is clearly not null?
HELP!
Solution
You could have a view model like this:
public class AddressViewModel
{
public string Postcode { get; set; }
}
and then use specify the Prefix
by decorating the parameter with the [Bind]
attribute:
[HttpGet]
public ActionResult PostcodeCheck(
[Bind(Prefix = "perinatalWomanView")]AddressViewModel model
)
{
// use model.Postcode here ...
}
or if you don't want to use the Bind
attribute have the following models:
public class MyViewModel
{
public AddressViewModel PerinatalWomanView { get; set; }
}
public class AddressViewModel
{
public string Postcode { get; set; }
}
and then have your controller action take the view model:
[HttpGet]
public ActionResult PostcodeCheck(MyViewModel model)
{
// use model.PerinatalWomanView.Postcode here ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow