页面加载时显示验证消息

发布于 2024-10-22 08:40:36 字数 1657 浏览 2 评论 0原文

我在 ASP.NET MVC 2.0 中遇到验证问题。我在控制器中使用相同的操作来执行用户请求。
例如:

public ActionResult Index(ReportModel model)
{
    if (!model.IsInitialDisplay && ModelState.IsValid)
    {
        model.Result = service.GetResult(model);                
    }
    return View(model);
}  

在 ReportModel 中,我定义了一个标志 IsInitialDisplay 来确定页面是否初始显示:

public class ReportModel
{
    [Required(ErrorMessage = "*")]
    public string Criteria { get; set; }
    public bool IsInitialDisplay { get; set; }
    public ReportResult Result { get; set; }

    public ReportModel()
    {
        IsInitialDisplay = true;
    }
}  

在 View 中,我使用以下代码:

<% using (Html.BeginForm())
   { %>
<table>
    <tr>
        <th>
            Criteria:
        </th>
        <td>
            <%= Html.TextBox("Criteria", "") %>
            <%= Html.ValidationMessage("Criteria") %>
        </td>
    </tr>
</table>
<br />
<input type="submit" value="Submit" />
<%= Html.Hidden("IsInitialDisplay", false) %>
<% } %>  

正如我所期望的,如果用户没有为 Criteria 输入任何值并单击提交按钮,将显示验证错误信息。
但验证错误消息总是在初始页面加载时显示,我不知道如何防止它?
有谁知道吗?谢谢,

[已更新]
我已经更新了我的 Action 方法,如下所示,看起来没问题:

public ActionResult Index(ReportModel model)
{
    // Collecting some commons data here...

    if (model.IsInitialDisplay)
    {
        ModelState.Clear();
    }
    else if (ModelState.IsValid)
    {
        model.Result = service.GetResult(model);                
    }
    return View(model);
}

I have a problem with validation in ASP.NET MVC 2.0. I use the same Action in Controller to perform user request.
For example:

public ActionResult Index(ReportModel model)
{
    if (!model.IsInitialDisplay && ModelState.IsValid)
    {
        model.Result = service.GetResult(model);                
    }
    return View(model);
}  

In the ReportModel, I define a flag IsInitialDisplay to determine whether the page is initial displayed or not:

public class ReportModel
{
    [Required(ErrorMessage = "*")]
    public string Criteria { get; set; }
    public bool IsInitialDisplay { get; set; }
    public ReportResult Result { get; set; }

    public ReportModel()
    {
        IsInitialDisplay = true;
    }
}  

And in the View, I use the following code:

<% using (Html.BeginForm())
   { %>
<table>
    <tr>
        <th>
            Criteria:
        </th>
        <td>
            <%= Html.TextBox("Criteria", "") %>
            <%= Html.ValidationMessage("Criteria") %>
        </td>
    </tr>
</table>
<br />
<input type="submit" value="Submit" />
<%= Html.Hidden("IsInitialDisplay", false) %>
<% } %>  

As I expect, if users don't input any value for Criteria and click Submit button, the error message for validation will be displayed.
But the validation error message always displayed on initial page load, I don't know how to prevent it?
Does anyone know? Thanks,

[Updated]
I have updated my Action method as below and it's seem to be fine:

public ActionResult Index(ReportModel model)
{
    // Collecting some commons data here...

    if (model.IsInitialDisplay)
    {
        ModelState.Clear();
    }
    else if (ModelState.IsValid)
    {
        model.Result = service.GetResult(model);                
    }
    return View(model);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

生来就爱笑 2024-10-29 08:40:36

初始页面加载时显示错误消息的原因是您的控制器操作采用 ReportModel 模型作为参数。当您首次使用 /Home/Index 访问此操作时,您没有传递任何参数,并且当默认模型绑定器尝试绑定到 ReportModel 实例时,它会触发验证错误。

使用相同的操作来渲染和处理表单提交是一种不好的做法,但如果您确实想要这样做,您可以尝试这样做:

public ActionResult Index(bool? isInitialDisplay)
{
    if (isInitialDisplay.HasValue && !isInitialDisplay.Value)
    {
        var model = new ReportModel();
        UpdateModel(model);
        if (ModelState.IsValid)
        {
            model.Result = service.GetResult(model);                
        }
        return View(model);
    }

    // Initial request
    return View(new ReportModel());
}

在这种情况下,您不再需要 IsInitialDisplay 属性您的模型或将其设置为 true 的构造函数。

话虽这么说,这是推荐的方法:

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

[HttpPost]
public ActionResult Index(ReportModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    model.Result = service.GetResult(model);                
    return View(model);
}

The reason an error message is displayed on initial page load is because your controller action takes ReportModel model as argument. When you first access this action with /Home/Index you are passing no arguments and when the default model binder tries to bind to a ReportModel instance it triggers validation errors.

It is a bad practice to use the same action for both rendering and handling the form submission but if you really want to do it you could try like this:

public ActionResult Index(bool? isInitialDisplay)
{
    if (isInitialDisplay.HasValue && !isInitialDisplay.Value)
    {
        var model = new ReportModel();
        UpdateModel(model);
        if (ModelState.IsValid)
        {
            model.Result = service.GetResult(model);                
        }
        return View(model);
    }

    // Initial request
    return View(new ReportModel());
}

In this case you no longer need the IsInitialDisplay property on your model nor the constructor which sets it to true.

This being said, here's the recommended way:

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

[HttpPost]
public ActionResult Index(ReportModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    model.Result = service.GetResult(model);                
    return View(model);
}
彩扇题诗 2024-10-29 08:40:36

这是一个简单的解决方案,结合了一些好的答案:

[HttpGet]
public ActionResult Index(ReportsModel model)
{
    ModelState.Clear(); //clears the validation

    return View(model);
}

[HttpPost]
public ActionResult Index(ReportsModel model, string unused)
{
    ...
}

这使用 http 方法来确定它是否是第一次加载(如 Darin 的解决方案)。

最重要的是,它使用 MVC 构建您的控制器,而不是您自己手动更新控制器。如果您使用依赖项注入或者您有其他上下文数据通过查询字符串传入(例如嵌套资源 ID),这一点很重要。

Here's a simple solution that combines some good answers:

[HttpGet]
public ActionResult Index(ReportsModel model)
{
    ModelState.Clear(); //clears the validation

    return View(model);
}

[HttpPost]
public ActionResult Index(ReportsModel model, string unused)
{
    ...
}

This uses the http method to determine if it's first load (like Darin's solution).

Most importantly, it has MVC build your controller instead of manually newing one up yourself. This is important if you use dependency injection or if you had other contextual data coming in through the query string (like a nested resource id).

够运 2024-10-29 08:40:36

模型

public class ReportModel
{
     [Required(ErrorMessage = "*")]
     public string Criteria { get; set; }
}

视图

<% Html.EnableClientValidation(); %>    

<% using (Html.BeginForm())
{ %>
     <%= Html.TextBoxFor(model => model.Criteria) %>
     <%= Html.ValidationMessageFor(model => model.Criteria) %>

     <input type="submit" value="Submit" />
<% } %>  

工作正常

Model

public class ReportModel
{
     [Required(ErrorMessage = "*")]
     public string Criteria { get; set; }
}

View

<% Html.EnableClientValidation(); %>    

<% using (Html.BeginForm())
{ %>
     <%= Html.TextBoxFor(model => model.Criteria) %>
     <%= Html.ValidationMessageFor(model => model.Criteria) %>

     <input type="submit" value="Submit" />
<% } %>  

Work fine

饭团 2024-10-29 08:40:36

如果您需要处理具有相同操作名称的表单提交,则应始终使用此技术:

[HttpGet]
public ActionResult Index()
{
    /* Just returning the view. No validation will happen because we are not passing a parameter*/
    return View();
}

[HttpPost]
public ActionResult Index(ReportsModel model)
{
    //Another post action for validation
}

If you need to handle form submission with the same action name, you should always use this technique:

[HttpGet]
public ActionResult Index()
{
    /* Just returning the view. No validation will happen because we are not passing a parameter*/
    return View();
}

[HttpPost]
public ActionResult Index(ReportsModel model)
{
    //Another post action for validation
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文