Validation messages are displayed when page load

孤人 提交于 2019-11-30 07:01:11
Darin Dimitrov

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);
}

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).

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!