ASP.NET MVC Unobtrusive validation - why form context is needed?

前端 未结 1 1706
你的背包
你的背包 2021-02-08 13:43

I\'m trying to enable unobtrusive javascript validation for dynamically created items. The problem with javascript was already solved in another SO question and this is not the

1条回答
  •  情书的邮戳
    2021-02-08 14:21

    You could manually fake a form context. For example if you had some partial view which doesn't contain a

    element and which is called using AJAX to regenerate some input elements you could do this:

    @model MyViewModel
    @{
        ViewContext.FormContext = new FormContext();
    }
    
    @Html.LabelFor(x => x.Foo)
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationMessageFor(x => x.Foo)
    

    The corresponding input elements will now posses the data-* attributes. But that might not be enough. If you are only refreshing (using AJAX) only a portion of the but not actually replacing the form element in the DOM calling $.validator.unobtrusive.parse wouldn't suffice. You need to remove any previous validations associated to this element:

    success: function(result) {
        // we are replacing only a portion of the form
        $('#somePartOfTheForm').html(result);
    
        $('form').removeData('validator');
        $('form').removeData('unobtrusiveValidation');
        $.validator.unobtrusive.parse('form');   
    }
    

    0 讨论(0)
提交回复
热议问题