我在搜索應用程序的MVC中使用了不顯眼的驗證,並且總體上它運行良好,除了兩件事我找不到任何答案。我之前使用過它,我不記得這些是一個問題,所以它可能只是我在這個應用程序中的設置。MVC不顯眼的驗證查詢
第一個問題是,它立即告訴我,搜索查詢輸入無效,或者至少顯示錯誤消息,儘管它是有效的開始。它通過模型添加了一些文本,所以在頁面加載時它有一個值,因此我不明白爲什麼不引人注意的驗證會失敗,並在加載時顯示錯誤消息。
第二個問題是,儘管是'required',並且'AllowEmptyStrings'設置爲false,並且'ConvertEmptyStringToNull'DisplayFormat還沒有看到空格(「」)字符串爲錯誤。我認爲這會趕上空白,但它沒有做到。
我已經克服了這兩個問題,第一個是通過在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, @"[‘’#[email protected]\$%]", "");
} 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>
以及調用此方案中的視圖(控制器,查詢爲空,所以它總是與SEARCHTERM集調用索引到「搜索網站」):
// 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));
}
預先感謝您的任何幫助,您可以給。我認爲代碼中沒有任何其他部分是相關的,但是請讓我知道是否需要查看更多內容,我會將其添加到問題中。
您是否可以檢查流量並確保沒有客戶端代碼在可能意外觸發的事件中將您的表單提交到某處? –
這意味着表單在加載頁面時立即提交,而且似乎並非如此。我在提交第二個問題時也有一些自定義驗證(所以它不提交空白搜索),並且在頁面加載時不會觸發,所以我不認爲這是問題。 –
沒有太多的代碼是合理的。首先,你得到了錯誤信息,因爲你的GET方法有一個參數供你模型使用,所以如果你不通過初始傳遞一個'SearchTerm'參數來調用它,就會添加一個'ModelState'錯誤(設置SearchTerm的值)其無效後不會消除錯誤)。其次,財產應該是一個簡單的'{get;組; }',如果你希望它遵循一個模式,你可以應用一個'[RegularExpression]'屬性。您的'