1

So I have this in my model:

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

And in my @using (Html.BeginForm I am using it like this:

    <div class="form-group">
        @Html.LabelFor(m => m.PasswordLoserFullName, "Name", new { @class = "control-label col-xs-2" })
        <div class="col-xs-6">
            @Html.TextBoxFor(m => m.PasswordLoserFullName, new { @class = "form-control"})
            @Html.ValidationMessageFor(m => m.PasswordLoserFullName)
        </div>
    </div>

The problem is as soon as page loads, it is showing the error message. Well yes the form just loaded, nobody has typed anything. I want it to show when user have clicked the Submit button. Not as soon as the page loads.

What is it that I am doing wrong?

Bohn
  • 26,091
  • 61
  • 167
  • 254
  • What does the action method rendering this view look like, and what have you tried? – CodeCaster Jun 13 '16 at 15:09
  • See [MVC Razor Validation Errors showing on page load when no data has been posted](http://stackoverflow.com/questions/21296281/mvc-razor-validation-errors-showing-on-page-load-when-no-data-has-been-posted), [Html.ValidationSummary(false, “message”) is always showing, even on page load](http://stackoverflow.com/questions/4166997/html-validationsummaryfalse-message-is-always-showing-even-on-page-load), [Validation messages are displayed when page load](http://stackoverflow.com/questions/5347827/validation-messages-are-displayed-when-page-load) and so on. – CodeCaster Jun 13 '16 at 15:10
  • 1
    Do not have a parameter in your GET method which is the model. If you need to pass values to the GET method, use parameters which are `string` etc and then initialize the model with those values in the GET method. –  Jun 13 '16 at 23:04

1 Answers1

1

I want it to show when user have clicked the Submit button. Not as soon as the page loads.

Then, it's a GET method which is getting called and for get method don't pass the model at all and just display the page. For POST method pass the model and perform validation.

Rahul
  • 76,197
  • 13
  • 71
  • 125
  • Hmm OK I see what you are saying. But even on GET part of the action method, for the request password form that is going to load, I still have some fields to show values from model so had to pass model, now I put some dummy value in the field for that one when loading the page but STILL it is showing the error. – Bohn Jun 13 '16 at 15:12
  • @Bohn, use the `[RequiredValidation]` attribute and set it to `false` since `GET` method doesn't actually require validation. – Rahul Jun 13 '16 at 15:18
  • hmm, I added this to top of that property, it says can't find such a thing :( [RequiredValidation = false] , how do you use it ? – Bohn Jun 13 '16 at 15:55
  • Ok this one worked: Adding "ModelState.Clear()" to the GET part. – Bohn Jun 13 '16 at 15:58