MVC4 远程验证未接收参数值

MVC4 Remote Validation Not Receiving Parameter Value

我正在尝试为视图中的字段实施远程验证。到目前为止一切正常,除了验证控制器方法中的参数为空,即使该字段包含一个值。我错过了什么?

验证控制器方法

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);
}

实体属性

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

查看

<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>

更新 重复 post 中的答案确实解决了问题。

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

    and add this to your view
    @{
    var VanityURL=Model.SelectedContact.WebSiteInfoes[0].VanityURL
    }



<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.TextBox("VanityURL",VanityURL,new { @class = "form-control", @placeholder = "Enter Vanity URL" })
        </div>
    </div>
</div>

我找到了避免更改 jquery.validate.js 文件的替代方法。这涉及在视图中设置 TextBoxFor 的名称,如下所示...

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

我还原了我的 js 文件更改,然后添加了视图名称属性和模型远程 AdditionalFields 定义的组合,它工作得很好。

此更改也导致了一些无法预料的问题。我终于得到了解决方案。我将 GET 更改为 POST 并从 FormsCollection 中获取了我需要的值。这 link 让我朝着正确的方向前进。这让我完全绕过了复杂数据对象命名问题