我在这里按照MVC教程添加搜索/过滤器文本框:
http://www.asp.net/mvc/overview/getting-started/introduction/adding-search
我已将过滤器文本框添加到我的页面:
@using (Html.BeginForm()) {
<p> Title: @Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" /></p>
}
如何在文本框中执行客户端验证以确保输入内容?
当您根据模型自动创建控制器和视图时,它会创建这个方便的HTML帮助程序:
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
类似的东西可以用于模型中没有的值,还是必须添加自定义jquery / html?
修改
感谢大家的指导。现在只需添加更多信息。我在现有模型中创建了一个新类:
public class SearchItem
{
[Required]
[StringLength(100, MinimumLength = 5, ErrorMessage = "This is my test error message")]
public string SearchString { get; set; }
}
然后在控制器内部,我创建了一个局部视图:
[ChildActionOnly]
[AllowAnonymous]
public PartialViewResult Search()
{
return PartialView();
}
然后我用:
创建了一个新的Search.cshtml@model App.Models.SearchItem
@using (Html.BeginForm())
{
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
<h4>@Html.LabelFor(model => model.SearchString, "Search:", htmlAttributes: new { @class = "control-label col-md-2" })</h4>
<div class="col-md-10 input-max-width">
@Html.EditorFor(model => model.SearchString, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.SearchString, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<input type="submit" value="Search" class="btn btn-primary" />
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
然后在我现有的页面上,我添加它:
@Html.Action("Search", "Items")
当我在文本框中没有输入文本并单击“搜索”按钮时,页面只会刷新,我没有得到客户端验证。
我的HTML看起来像这样:
<form action="/Items/Index" method="post"> <div class="form-group">
<h4><label class="control-label col-md-2" for="SearchString">Search:</label></h4>
<div class="col-md-10 input-max-width">
<input class="form-control text-box single-line" data-val="true" data-val-length="This is my test error message" data-val-length-max="100" data-val-length-min="5" data-val-required="The SearchString field is required." id="SearchString" name="SearchString" type="text" value="" />
<span class="field-validation-valid text-danger" data-valmsg-for="SearchString" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Search" class="btn btn-primary" />
</div>