Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation messages are displayed when page load

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);
}
like image 221
aquanilium Avatar asked Mar 18 '11 03:03

aquanilium


People also ask

How do you show validation messages?

How do you display a validation message specific to a field in a Blazor form? You have to use the <ValidationMessage> tag with the “For” attribute lambda expression pointing to the form field.

What does validation message mean?

If there are any validation messages, the focus is set to the first invalid input: this way, a screen reader will immediately announce the associated message, so the user knows that there is at least one invalid input to be fixed.

Which HTML helpers are used to show the validation messages?

ValidationMessage(HtmlHelper, String, Object) Displays a validation message if an error exists for the specified field in the ModelStateDictionary object.

What is validation in ASP NET MVC?

Validation is an important aspect in ASP.NET MVC applications. It is used to check whether the user input is valid. ASP.NET MVC provides a set of validation that is easy-to-use and at the same time, it is also a powerful way to check for errors and, if necessary, display messages to the user.


1 Answers

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);
}
like image 172
Darin Dimitrov Avatar answered Oct 04 '22 21:10

Darin Dimitrov