如何以编程方式触发Razor视图设置的客户端验证?

时间:2021-04-14 20:14:28

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:

我有一个小的Ajax应用程序,我使用Razor视图来初始生成HTML表单段,我稍后使用knockout.js读取和写入。虽然我没有执行非Ajax操作请求,但我使用Razor生成HTML,因此我喜欢自动生成jQuery Validation属性。例如。在我的单页中,我渲染一个隐藏的表单,如下所示:

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

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

EditPartial操作返回一个看起来很像这样的局部视图:

@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?

因为我实际上从未发布过该表单,并且由于一些未知数,尽管我的Person模型上的所有属性都标有Required属性,但我看不到客户端验证的迹象。单击我的保存按钮时,我该怎么做才能触发此验证?

1 个解决方案

#1


10  

suppose your form has a class 'main':

假设您的表单有一个类'main':

    $('form').submit(function() {
            var $form = $('form.main');
            $form.valid();
    });

#1


10  

suppose your form has a class 'main':

假设您的表单有一个类'main':

    $('form').submit(function() {
            var $form = $('form.main');
            $form.valid();
    });