我正在尝试为视图中的字段实施远程验证。到目前为止的所有工作都在工作,除非验证控制器方法中的参数为null,即使该字段包含值。我错过了什么?
验证控制器方法
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>
UPDATE 重复帖子中的答案可以解决问题。
答案 0 :(得分:0)
我找到了另一种避免更改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让我朝着正确的方向前进。这使我完全绕过了复杂数据对象命名问题
答案 1 :(得分:-1)
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>