相关疑难解决方法(0)

使用ASP.NET MVC验证与jquery ajax?

我有这样简单的ASP.NET MVC动作:

public ActionResult Edit(EditPostViewModel data)
{

}
Run Code Online (Sandbox Code Playgroud)

EditPostViewModel具有验证属性是这样的:

[Display(Name = "...", Description = "...")]
[StringLength(100, MinimumLength = 3, ErrorMessage = "...")]
[Required()]
public string Title { get; set; }
Run Code Online (Sandbox Code Playgroud)

在视图中,我使用以下帮助程序:

 @Html.LabelFor(Model => Model.EditPostViewModel.Title, true)

 @Html.TextBoxFor(Model => Model.EditPostViewModel.Title, 
                        new { @class = "tb1", @Style = "width:400px;" })
Run Code Online (Sandbox Code Playgroud)

如果我在表单上提交此文本框放在验证中,将首先在客户端上完成,然后在service(ModelState.IsValid)上完成.

现在我有几个问题:

  1. 这可以与jQuery ajax提交一起使用吗?我正在做的只是删除表单,然后单击提交按钮javascript将收集数据,然后运行$.ajax.

  2. 服务器端会ModelState.IsValid工作吗?

  3. 如何将验证问题转发回客户端并将其呈现为使用build int validation(@Html.ValidationSummary(true))?

Ajax调用示例:

function SendPost(actionPath) {
    $.ajax({
        url: actionPath,
        type: 'POST',
        dataType: 'json',
        data:
        {
            Text: $('#EditPostViewModel_Text').val(), …
Run Code Online (Sandbox Code Playgroud)

validation ajax asp.net-mvc jquery

116
推荐指数
4
解决办法
13万
查看次数

在Ajax提交之前进行jQuery表单验证

JavaScript位:

$(document).ready(function()
    {
            $('#form').submit(function(e)
            {     

                e.preventDefault();
                var $form = $(this);

                // check if the input is valid
                if(! $form.valid()) return false;
                    $.ajax(
                    {
                    type:'POST',
                    url:'add.php',
                    data:$('#form').serialize(),
                    success:function(response)
                    {
                        $("#answers").html(response);
                    }
                });     

            })
    });
Run Code Online (Sandbox Code Playgroud)

HTML位:

    <input type="text" name="answer[1]" class="required" />
    <input type="text" name="answer[2]" class="required" />
Run Code Online (Sandbox Code Playgroud)

所以这是我试图使用的代码.我的想法是在我用Ajax发送表单之前验证我的所有输入.我现在已经尝试了很多版本,但每次我最终都提交,即使表格没有完全填写.我的所有输入都是"必需"类.谁能看到我做错了什么?

此外,我依赖基于类的要求,因为我的输入名称是用PHP生成的,所以我永远无法确定我得到的名称[id]或输入类型.

当我在"页面"中浏览时,我会显示/隐藏问题.

<input type="button" id="next" onClick="toggleVisibility('form3')" class="next-btn"/>
Run Code Online (Sandbox Code Playgroud)

JS:

function toggleVisibility(newSection) 
        {
            $(".section").not("#" + newSection).hide();
            $("#" + newSection).show();
        } 
Run Code Online (Sandbox Code Playgroud)

validation ajax jquery jquery-validate

41
推荐指数
5
解决办法
21万
查看次数

标签 统计

ajax ×2

jquery ×2

validation ×2

asp.net-mvc ×1

jquery-validate ×1