[英]MVC unobtrusive validation queries
我在MVC中为搜索应用程序使用了不打扰的验证,并且总体上它运行良好,除了2件事我找不到任何答案。 我以前使用过它,并且我不记得这些是一个问题,因此它可能只是我在此应用程序中的设置。
第一个问题是它立即告诉我搜索查询输入是无效的,或者至少显示了错误消息,尽管它最初是有效的。 它通过模型向其中添加了一些文本,因此在页面加载时它具有一个值,因此我无法理解为什么非干扰性验证会使它失败并在加载时显示错误消息。
第二个问题是,尽管被“要求”并且将“ AllowEmptyStrings”设置为false,但它并没有将空格(“”)字符串视为错误,以及显示格式'ConvertEmptyStringToNull'。 我以为这会赶上空白,但没有成功。
我已经克服了这两个问题,首先是通过在Document.Ready中手动调用验证来证明输入确实有效。 第二种是在提交表单之前添加手动检查。 两者都是令人费解的,尤其是第一个问题,我想知道为什么它不能按预期工作,并在将来避免这个问题
代码的相关部分如下:
具有searchTerm属性和注释的SearchVM视图模型。
public class SearchVM : PageDetails
{
public string SpellingSuggestion { get; set; }
public List<Result> SearchResults { get; set; }
public int ResultsCount { get; set; }
private string searchTerm = "";
[Display(Name = "Search the website")]
[Required(ErrorMessage = "Please enter a search term", AllowEmptyStrings = false)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string SearchTerm { get
{
return searchTerm;
}
set {
//Strip out bad characters from the search term
if (value != null) {
searchTerm = Regex.Replace(value, @"[‘’#!@\$%]", "");
} else
{
searchTerm = "";
}
}
}
}
显示查询的索引视图:
@model SearchVM
@{
Model.Title = "Search the website";
Model.Description = "Search the website.";
Model.Keywords = ", website, search, google, find, websearch";
Model.Class = "search";
}
<main class="search">
@using (Ajax.BeginForm("Results", new AjaxOptions { UpdateTargetId = "results", OnComplete= "moreInfoDropDown(), spellingSuggestion()" }))
{
@Html.LabelFor(m => m.SearchTerm)
<div>
@Html.TextBoxFor(m => m.SearchTerm, new { maxlength = 30, autocomplete = "off" })
</div>
<input type="image" src="~/Images/search/icon.png" alt="Search" tabindex="3" />
@Html.ValidationMessageFor(m => m.SearchTerm)
}
<div id="results">
@if (Model.SearchResults != null)
{
@Html.Partial("_ResultsIntro", Model)
}
</div>
</main>
以及调用该视图的控制器(在这种情况下,查询为null,因此它将始终调用searchTerm设置为“ Search the website”的Index):
// GET: Search
public ActionResult Index(SearchVM searchVM, string query)
{
// If there is a query added to the URL, use it
if (!string.IsNullOrWhiteSpace(query)) {
searchVM.SearchTerm = query;
}
// Re-load the typical index with no results if the search term is empty
if (string.IsNullOrWhiteSpace(searchVM.SearchTerm))
{ return View(new SearchVM() { SearchTerm = "Search the website" });
}
// Return the index with the queried result (if applicable)
return View(GSA.Query(searchVM.SearchTerm, 0));
}
预先感谢您提供的任何帮助。 我认为代码的任何其他部分都不相关,但是如果您需要更多内容,请告诉我,我将其添加到问题中。
正如Stephen Muecke在他的评论中所说,我错误地将searchVM模型传递给了控制器,因此在传递给视图之前它已经是无效的。 删除该参数,然后初始化模型的新实例解决了该问题。
感谢斯蒂芬指出这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.