Null values when using remote validation in MVC3

3k Views Asked by At

I am having a problem with remote validation.

I have a viewmodel with a property on which I have added a Remote validator but when I run the form and enter a string in the text box the value passed to the controller is null.

The property in the viewmodel looks like this:

[Required(ErrorMessage = "Enter the host's name")]
[Remote("ValidateHostFullName", "BoardroomBooking", ErrorMessage = "Enter a different name")]
[DisplayName("Host's Name")]
public string HostFullName { get; set; }

The code for the validator in the Controller looks like this:

public ActionResult ValidateHostFullName([Bind(Prefix="BookingReceptionViewModel")]string HostFullName)
{
    if (!HostFullName.Equals("John Smith"))
    {
        return Json(true, JsonRequestBehavior.AllowGet);
    }

    return Json("{0} is not allowed", JsonRequestBehavior.AllowGet);
}

The value of the string for HostFullName shows as null no matter what is typed in the box. I have tried it with and without the Bind Prefix and that makes no difference.

I've tried this on a model and it works, it only seems to have an issue when I use a viewmodel.

Thanks

Mark

2

There are 2 best solutions below

0
On

I had the same problem. The rendered html control was NOT prefixed by class name but in remote validation code, I had binded by prefixing the classname.propertyname. Removing this binding solved my problem. Or else by prefixing only property name also works fine for me.

1
On

I was having the same issue. The parameter coming into ValidateHostFullName() must be the same as the input name.