【问题标题】:MVC-5 Razor Validation Errors showing on page load页面加载时显示 MVC-5 Razor 验证错误
【发布时间】:2017-10-21 16:30:12
【问题描述】:

当我转到插入页面时,我有一个插入页面,所有验证字段都显示出来,

[Required(ErrorMessage ="Please Enter Name")]
        public string ccname { get; set; }

这是我的班级,我用所需的验证消息声明字符串 ccname

输入姓名

它应该在用户点击插入而不在ccname中输入数据时出现

但页面加载时会显示验证消息

@Html.TextBoxFor(model => model.ccname, new { @class = "textboxstyle" })
@Html.ValidationMessageFor(model => model.ccname)

我尝试了一些东西,但没有任何效果,

这是一个例子

在我的控制器中我添加了ModelState.clear();

public ActionResult insert()
{
    ModelState.Clear();
    return View();
}

在我看来,我更改了代码

@Html.TextBoxFor(model => model.ccname, new { @class = "textboxstyle" })
@Html.ValidationMessageFor(model => model.ccname)

@Html.TextBoxFor(model => model.ccname, new { @class = "textboxstyle" })
@Html.ValidationMessageFor(model => model.ccname,"",new {@style= ".validation-summary-valid { display:none; }" })

但这些都不起作用

我现在该怎么办?

【问题讨论】:

  • insert() 方法是您的实际控制器方法还是只是一个示例?
  • 我没有在我的插入 [httppost] 方法中写任何东西
  • 首先,您提供的代码不起作用,因为您没有将view model 传递给您的view
  • @MumbaiWadala 这不是问题所在。如果这不是您的 Get 方法的实际代码,请发布实际代码。
  • @Marco 这是我的控制器的实际方法此方法在页面加载时触发public ActionResult insert() { return View(); }

标签: asp.net-mvc validation razor asp.net-mvc-5


【解决方案1】:

示例:

型号:

public class MyModel
{
  [Required(ErrorMessage ="Please Enter Name")]
  public string ccname { get; set; }
}

控制器:

public class HomeController:Controller
{
[HttpGet]
 ActionResult Insert()
 {
     var model =new MyModel();
      return View(model); 
 }

 [HttpPost]
 [ValidateAntiForgeryToken]
 ActionResult Insert(MyModel model)
 {
     if(ModelState.IsValid)
     {
      //Do something
       return View(); 
     }   
      return View(model); 
 }
}

查看

插入.cshtml

@model MyModel

@using (Html.BeginForm("Insert", "Home", FormMethod.Post))
{
 @Html.AntiForgeryToken()
 @Html.ValidationSummary(true, "", new { @class = "text-danger" })
 @Html.TextBoxFor(model => model.ccname, new { @class = "textboxstyle" })
 @Html.ValidationMessageFor(model => model.ccname)
  <input type="submit" value="Insert" class="btn btn-primary" />
}
@Scripts.Render("~/bundles/jqueryval")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 2017-02-27
    • 2023-04-09
    相关资源
    最近更新 更多