【问题标题】:Why is my ValidationMessageFor For TextArea Displaying on Page Load为什么我的 ValidationMessageFor For TextArea 在页面加载时显示
【发布时间】:2012-03-09 20:11:26
【问题描述】:

当我的页面加载时,我的 ValidationSummary 和 ValidationMessageFor(model => model.TestNumbersString) 都显示验证错误,尽管几乎没有加载页面。我检查了 .css 文件是否在我的 _Layout.cshtml 中被引用,并且样式存在。

模型.cs

[Required]
public string TestNumbersString { get; set; }

HomeController.cs

public ActionResult Index(TestModel model)
{
    return View(model);
}

partialView.cshtml

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = "form" }))
{
    @Html.TextAreaFor(model => model.TestNumbersString, new { @class = "testBox" })
    @Html.ValidationMessageFor(model => model.TestNumbersString)
}

我注意到我的布局有许多 javascript 和 css 文件,但其他验证在页面上有效,并且我知道 site.css 已为页面的其他部分加载(但不是为我的表单,但这是另一个问题)。

_Layout.cshtml

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />

到目前为止,我所做的故障排除使我发现验证消息的类是 field-validation-error。所以我相信这不是 .css 错误(即使 css 样式应用不正确)。

我还想明确一点,这是一个部分布局。我不确定这在处理验证时是否会导致其他问题。

编辑:解决方案

感谢@jacqijvv 的解决方案。

public ActionResult Index()
{
    TestModel model = new TestModel();
    return View(model);
}

[HttpPost]
//We have these separate as this is the design for MVC.
public ActionResult Index(TDMixParametersViewModel model)
{
    if (ModelState.IsValid)
        return View(model);
    else
    {
        model = new TDMixParametersViewModel();
        return View(model);
    }
}

【问题讨论】:

    标签: c# asp.net-mvc-3 razor validation


    【解决方案1】:

    从动作方法调用中移除参数

    例如

        public ActionResult Index()
        {
            TestModel model = new TestModel();
            return View(model);
        }
    

    这应该可以解决问题

    【讨论】:

    • 这修复了它。如果你有时间,你能给我解释一下为什么会这样吗?
    • Quickhorn,这是因为 MVC 内置路由的工作方式。 HTTPGET 函数,即您调用的 Index 操作,不需要模型作为参数,这就是验证立即失败的原因。默认值是无参数或 id,对于 HTTPGET 方法和 HTTPPOST 方法,它是 FormCollection 或模型,因为它在提交表单时回发这些值。或者类似的东西:-)
    • @jacqijw 谢谢!我将我的反应分为两个动作。所有的教程都有你这样做,但我一直在搞乱,从来没有切换回这两个动作。我从没想过它会破坏验证。
    【解决方案2】:

    您的 css 文件包含在页面顶部,对吗?建议将css文件放在head的顶部,javascript文件放在body的末尾

    尝试将 site.css 文件放在 _layout.cshtml 中的 JavaScript 文件之前

    【讨论】:

    • 我只是尝试将 JS 文件移动到正文的末尾,但不幸的是,它并没有解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    相关资源
    最近更新 更多