简体   繁体   English

MVC不干扰验证查询

[英]MVC unobtrusive validation queries

I'm using unobtrusive validation in MVC for a search application, and on the whole it works well, except for 2 things that I can't find any answers for. 我在MVC中为搜索应用程序使用了不打扰的验证,并且总体上它运行良好,除了2件事我找不到任何答案。 I've used it before, and I don't remember these being an issue, so it could just be my setup in this application. 我以前使用过它,并且我不记得这些是一个问题,因此它可能只是我在此应用程序中的设置。

The first issue is that it immediately tells me that the search query input is invalid, or at least shows the error message for it, despite it being valid to begin with. 第一个问题是它立即告诉我搜索查询输入是无效的,或者至少显示了错误消息,尽管它最初是有效的。 It has some text added to it via the model, so it has a value when the page loads, therefore I can't understand why the unobtrusive validation fails it and shows the error message it when it loads. 它通过模型向其中添加了一些文本,因此在页面加载时它具有一个值,因此我无法理解为什么非干扰性验证会使它失败并在加载时显示错误消息。

The second issue is that it doesn't see a whitespace (" ") string as an error despite being 'required' and having 'AllowEmptyStrings' set to false, along with a 'ConvertEmptyStringToNull' DisplayFormat. 第二个问题是,尽管被“要求”并且将“ AllowEmptyStrings”设置为false,但它并没有将空格(“”)字符串视为错误,以及显示格式'ConvertEmptyStringToNull'。 I thought this would catch the whitespace, but it isn't doing. 我以为这会赶上空白,但没有成功。

I've overcome both these issues, the first by calling the validation manually in Document.Ready, which proves that the input is indeed valid. 我已经克服了这两个问题,首先是通过在Document.Ready中手动调用验证来证明输入确实有效。 And the second by adding a manual check before the form is submitted. 第二种是在提交表单之前添加手动检查。 Both of these are convoluted, especially the first issue, I'd like to know why it doesn't work as expected, and avoid this issue in the future 两者都是令人费解的,尤其是第一个问题,我想知道为什么它不能按预期工作,并在将来避免这个问题

The relevant parts of the code are below: 代码的相关部分如下:

The SearchVM view model with the searchTerm property and the annotations. 具有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 = "";
            }
        }
    }
}

The Index view where the query is displayed: 显示查询的索引视图:

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

And the controller that calls the view (in this scenario, the query is null, so it always calls the Index with the searchTerm set to "Search the website"): 以及调用该视图的控制器(在这种情况下,查询为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));
}

Thank you in advance for any help you can give. 预先感谢您提供的任何帮助。 I don't think any other parts of the code are relevant, but please let me know if you need to see more, and I will add it to the question. 我认为代码的任何其他部分都不相关,但是如果您需要更多内容,请告诉我,我将其添加到问题中。

As Stephen Muecke said in his comment, I was incorrectly passing the searchVM model to the controller, and therefore it was already invalid before being passed to the view. 正如Stephen Muecke在他的评论中所说,我错误地将searchVM模型传递给了控制器,因此在传递给视图之前它已经是无效的。 Removing that parameter, and instead initialising a new instance of the model solved the issue. 删除该参数,然后初始化模型的新实例解决了该问题。

Thanks to Stephen for pointing this out. 感谢斯蒂芬指出这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM