0

How do I avoid postback for validation when I press Submit? When pressing submit, the page reload/postback and THEN it gives me the validation error.

@model X.Models.ModelVm

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Birthday, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Birthday, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Birthday, "", new { @class = "text-danger" })             
            </div>
        </div>

        .....

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Get data" class="btn btn-default"/>                   
            </div>
        </div>
    </div>
}

My ViewModel:

[Required]
[DataType(DataType.DateTime)]
public DateTime Birthday { get; set; }
sav
  • 11
  • 4

1 Answers1

2
  1. Turn on ClientValidationEnabled and UnobtrusiveJavaScriptEnabled.
  2. Include jquery, jquery.validate.js, jquery.validate.unobtrusive.js in Your view.
hekta
  • 126
  • 1
  • 3
  • Awesome, it's working! Thanks :) Btw Is there any way I can turn on `ClientValidationEnabled` and `UnobtrusiveJavaScriptEnabled` once per controller or do I have add it each time when I need it for a specific methods in controller? – sav Dec 19 '16 at 18:58
  • Yes, You can add entries in Web.config file like [here](http://stackoverflow.com/a/4358955/6712547) – hekta Dec 19 '16 at 20:01