Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Remote validation, parameter is null

public class UserModel
    {
        public LogOnModel LogOnModel { get; private set; }
        public RegisterModel RegisterModel { get; private set; }
    }

in my RegisterModel I have email address like this:

[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")]
        [Required]
        [Display(Name = "E-mail")]
        [Remote("IsEmailAddressAvailable", "Validation", HttpMethod = "POST")]
        public string EmailAddress { get; set; }

My validationController:

public class ValidationController : Controller
    {
        public JsonResult IsEmailAddressAvailable([string emailAddress)
        {
            return Json(false, JsonRequestBehavior.AllowGet);

        }
}

The view @Model is UserProfile, the emailAddress in ValidationController is null.

I tried to change the ValidationController to look like this with no luck:

public class ValidationController : Controller
    {
        public JsonResult IsEmailAddressAvailable([Bind(Include = "EmailAddress")]RegisterModel register)
        {
            return Json(false, JsonRequestBehavior.AllowGet);

        }


    }
like image 468
Pacman Avatar asked Oct 11 '12 21:10

Pacman


2 Answers

Your thinking about using Bind attribute is correct. Instead using Include parameter, you should use Prefix parameter. So your controller should look:

public class ValidationController : Controller
    {
        public JsonResult IsEmailAddressAvailable([Bind(Prefix = "RegisterModel.EmailAddress")]string EmailAddress)
        {
            return Json(false, JsonRequestBehavior.AllowGet);

        }
    }

So Prefix parameter binds parameter sent by browser with action parameter.

like image 74
Miron Avatar answered Oct 21 '22 05:10

Miron


I would suspect this to be a model binding issue. Try changing the action signature to something like this:

public class ValidationController : Controller
{
    public JsonResult IsEmailAddressAvailable([Bind(Prefix="RegisterModel")]string emailAddress)
    {
        return Json(false, JsonRequestBehavior.AllowGet);
    }
}

Notice the [Bind(Prefix="RegisterModel")], which was slightly similar to what you were trying to do from your latter attempt, so I think you were on the right track. I basically pulled this from a very similar answer posted here, so maybe that trail can help you out further if this doesn't quite do it for you.

like image 3
DMac the Destroyer Avatar answered Oct 21 '22 04:10

DMac the Destroyer