Search code examples
c#asp.net-mvcvalidationasp.net-mvc-4jquery-validation-engine

MVC4 Remote Validation Not Receiving Parameter Value


I'm trying to implement Remote Validation for a field in a view. Everything so far is working except the parameter in the validation controller method is null even though the field contains a value. What did I miss?

Validation Controller Method

public JsonResult IsVanityURL_Available(string VanityURL)
{
    if (!_webSiteInfoRepository.GetVanityURL(VanityURL))
        return Json(true, JsonRequestBehavior.AllowGet);

    string suggestedUID = String.Format(CultureInfo.InvariantCulture,
        "{0} is not available.", VanityURL);

    for (int i = 1; i < 100; i++)
    {
        string altCandidate = VanityURL + i.ToString();
        if (_webSiteInfoRepository.GetVanityURL(altCandidate)) continue;
        suggestedUID = String.Format(CultureInfo.InvariantCulture,
            "{0} is not available. Try {1}.", VanityURL, altCandidate);
        break;
    }
    return Json(suggestedUID, JsonRequestBehavior.AllowGet);
}

Entity Property

[DisplayName("Vanity URL")]
[Remote("IsVanityURL_Available", "Validation")]
[RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")]
[Editable(true)]               
public string VanityURL { get; set; }

View

<div class="row">
    <div class="form-group col-md-12">
        <div class="editor-label">
            @Html.LabelFor(model => model.SelectedContact.WebSiteInfoes[0].VanityURL)
        </div>
        <div class="input-group margin-bottom-small">
            <span class="input-group-addon"><i class="fa fa-external-link-square fa-fw"></i></span>
            @Html.TextBoxFor(model => model.SelectedContact.WebSiteInfoes[0].VanityURL, new { @class = "form-control", @placeholder = "Enter Vanity URL" })
        </div>
    </div>
</div>

UPDATE The answer in the duplicate post does fix the problem.


Solution

  • I found an alternate way to avoid changing the jquery.validate.js file. This involved setting the name of the TextBoxFor in the view like so...

    @Html.TextBoxFor(model => model.SelectedContact.WebSiteInfoes[0].VanityURL, new { @class = "form-control", @placeholder = "Enter Vanity URL", @Name="VanityUrl })
    

    I reverted my js file change, then added a combination of the view name attribute and the model remote AdditionalFields definition and it worked just fine.

    This change caused some unforeseen problems as well. I finally did get a solution. I changed the GET to a POST and grabbed the values I needed from the FormsCollection. This link got me going in the right direction. This allowed me to completely bypass the Complex Data Object naming problem