Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically trigger client side validation set up by a Razor view?

I have a little Ajax application where I use Razor views to initially generated HTML form segments that I later read and write from with knockout.js. Although I am doing no non-Ajax action requests, I use Razor to generate the HTML so I enjoy automatic generation of jQuery Validation attributes. E.g. in my single page, I render a hidden form like this:

<section id="person-detail">
    @Html.Action("EditPartial", "Person")
</section>

The EditPartial action returns a partial view that looks a lot like this:

@using (Html.BeginForm())
{
    <fieldset>
        @Html.HiddenFor(model => model.Id, new { data_bind = "value: id" })
        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.FirstName, new { data_bind = "value: firstName" })
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>
        <p>            
            <a href="#" data-bind="click: save">Update</a>&nbsp;&nbsp;
            <a href="#" data-bind="click: delete">Delete</a>
        </p>
    </fieldset>
}

Because I'm never actually posting the form, and due to some unknowns, despite all properties on my Person model being marked with the Required attribute, I see no sign of client side validation. What must I do to trigger this validation when my save button is clicked?

like image 404
ProfK Avatar asked Oct 15 '12 18:10

ProfK


People also ask

How do I enable client-side validation?

We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level. For client-side validation, the values of above both the keys must be true.

Where can client-side validation be deactivated globally for all razor views?

You can simply disable client side validation in the Razor view prior to render the field and re-enable client side validation after the field has been rendered.

How client-side validation is implemented in MVC?

Firstly, you just need to create an ASP.NET MVC application. To create a new ASP.NET MVC application, Open Visual Studio choose File, New, then Project. It will open a New Project window, from where you need to choose node Visual C# and then Web and from the right pane you need to choose ASP.NET Web Application.


1 Answers

suppose your form has a class 'main':

    $('form').submit(function() {
            var $form = $('form.main');
            $form.valid();
    });
like image 127
ShaneKm Avatar answered Sep 17 '22 11:09

ShaneKm