【发布时间】:2019-10-10 11:43:40
【问题描述】:
我在显示模型错误时遇到问题。当我使用强绑定表单时显示模型错误。但是当我不使用强数据绑定时,它不会显示模型错误。那么我如何显示模型错误或验证没有强绑定,以及为什么它没有显示模型错误而没有强绑定。 p>
控制器
public ActionResult productFilter()
{
catName();
return View();
}
[HttpPost]
public ActionResult productFilter(productFilterModel filter)
{
catName();
if(ModelState.IsValid)
{
//other operations here
}
return View();
}
型号
public class productFilterModel
{
[Required]
public string catName { get; set; }
[Required]
public int maxPrice { get; set; }
[Required]
public int minPrice { get; set; }
}
查看
@model RentalServices.Models.productFilterModel
// with strongly binding form and showing model error
<form action="/Product/productFilter" method="post">
<label>Category</label>
@Html.DropDownListFor(model => model.catName, ViewBag.catName as SelectList, "CHOOSE CATEGORY", new { @class = "form-control"})
@Html.ValidationMessage("catName", new { @class = "text-danger" })
<label>Min Price</label>
@Html.TextBoxFor(model => model.minPrice, new { @class = "form-control"})
@Html.ValidationMessage("minPrice", new { @class = "text-danger" })
<label>Mxn Price</label>
@Html.TextBoxFor(model => model.maxPrice, new { @class = "form-control"})
@Html.ValidationMessage("maxPrice", new { @class = "text-danger" })
<button type="submit">Submit</button>
</form>
// without strongly binding form and not showing model error
<form action="/Product/productFilter" method="post">
<label>Category</label>
<select name="catName">
<option value="1">mobile</option>
<option value="2">laptop</option>
<option value="3">printer</option>
</select>
@Html.ValidationMessage("catName", new { @class = "text-danger" })
<label>Min Price</label>
<input type= "number" name="minPrice" />
@Html.ValidationMessage("minPrice", new { @class = "text-danger" })
<label>Max Price</label>
<input type= "number" name="maxPrice" />
@Html.ValidationMessage("maxPrice", new { @class = "text-danger" })
<button type="submit">Submit</button>
</form>
【问题讨论】:
-
你需要手动验证,你可以在MVC中使用jquery validator方法
-
我已经在使用
jquery.validate.unobtrusive.js和jquery.validate.js,但没有强绑定表单时不会显示错误。 -
检查this链接。希望对您有所帮助
-
您可以使用 while button click check
$("form").valid()if form return true 然后提交您的表单
标签: c# asp.net-mvc validation