【问题标题】:Show model error on view without strongly binding asp.net MVC在没有强绑定 asp.net MVC 的情况下在视图上显示模型错误
【发布时间】: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.jsjquery.validate.js,但没有强绑定表单时不会显示错误。
  • 检查this链接。希望对您有所帮助
  • 您可以使用 while button click check $("form").valid() if form return true 然后提交您的表单

标签: c# asp.net-mvc validation


【解决方案1】:

模型错误是针对强类型的,但是如果您不想使用强类型视图,那么您必须创建自定义验证。其中一种方法是在控制器中您可以检查该字段是否为空,如果如果为 null,则可以使用 TempData 打印错误消息

【讨论】:

  • 我认为检查每个字段是一个漫长的过程。如果我想用正则表达式检查验证怎么做?如果我对单个属性有多个验证,那么我必须检查每个属性的每个验证,所以我认为这不公平。
猜你喜欢
  • 1970-01-01
  • 2011-05-11
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 1970-01-01
相关资源
最近更新 更多