如果我在jQuery UI对话框中运行表单,如何处理服务器端验证错误?

时间:2022-01-10 16:11:49

I have the following code in my controller after the user posts the form but if the validation fails (_applicationValidator.Validate), I normally reload the "Edit" view but in this case I want to keep the dialog open and simply show these errors inside the dialog.

用户发布表单后,我的控制器中有以下代码,但如果验证失败(_applicationValidator.Validate),我通常会重新加载“编辑”视图,但在这种情况下我想保持对话框打开,只是在里面显示这些错误对话框。

Controller Code:

  [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Update(ApplicationUpdater applicationUpdater_)
    {
        if (_applicationValidator.Validate(applicationUpdater_, ModelState, ValueProvider))
        {
            _repo.UpdateApplication(applicationUpdater_);
            ApplicationsViewModel vm = new ApplicationsViewModel();
            vm.Applications = _repo.GetApplications();
            return View("Index", vm);
        }
        else
        {
            ApplicationViewModel vm = GetApplicationVM();
            return View("Edit", vm);
        }
    }

View Code (jQuery)

查看代码(jQuery)

 $(".showEditPopup").click(function() {
            $.post("Applications/ShowEdit",
                { recnum: $(this).parents('tr:first').attr("recnum") },
                function(htmlResult) {
                    $("#EditUserControlDiv").remove();
                    $("#container").append(htmlResult);
                    $("#container select[multiple]").asmSelect();
                    $("#EditUserControlDiv").dialog(
                    {
                        height: 675,
                        width: 650,
                        modal: true
                    }
                    );
                }
           );
        });

3 个解决方案

#1


5  

As said

But in this case i want to keep the dialop open and simply show these errors inside the dialog

但在这种情况下,我想保持拨号盘打开,只是在对话框中显示这些错误

Ok.

After openning the dialog, you have to

打开对话框后,您必须这样做

  • hide previous error message
  • 隐藏上一条错误消息

...

open: function(event, ui) {
    $(".error").css("display", "none");
}

After clicking dialog button, you have to

单击对话框按钮后,您必须

  • disable JQuery UI
  • 禁用JQuery UI

  • Show "loading..." image
  • 显示“loading ...”图像

  • Send form

...

$("#loading").css("display", "block");

panel.dialog("disable");

panel.dialog("option", "disabled", true);

After response is loaded (You can use JSON as response), you have to

加载响应后(您可以使用JSON作为响应),您必须

  • Check whether it has errors.
  • 检查是否有错误。

...

// var response plays the role of JSON response

var response = {
    "errors":[
        {
            "property-name":"name",
            "error":"Name is required"
        },
        {
            "property-name":"age",
            "error":""
        }
    ]
};

var hasErrors = false;

for(var i = 0; i < response.errors.length; i++) {
    if(response.errors[i].error != "") {
         hasErrors = true;

         $("#" + response.errors[i]["property-name"] + "-error")
           .text(response.errors[i]["error"])
           .css("display", "block");
    }
}

if(!hasErrors) {
    panel.dialog("close");

    alert("success form!");
} else {
    panel.dialog("enable");

    panel.dialog("option", "disabled", false);
}

Here you can see in Action

在这里你可以看到行动

Notice you have a default behavior. So you can put it inside a external function

请注意,您有默认行为。所以你可以将它放在一个外部函数中

#2


1  

Most convenient:

  • Disable all input elements
  • 禁用所有输入元素

  • Do an Ajax post to the Update function
  • 对Update函数执行Ajax发布

  • Handle the server response in your UI. E.g. closing the jQuery UI form, or showing validation errors.
  • 在UI中处理服务器响应。例如。关闭jQuery UI表单,或显示验证错误。


Change your Update function to return some wrapper object like:

更改您的Update函数以返回一些包装器对象,如:

return new { Succeeded = false, ValidationMessages = new [] { "Incorrect username" } };

$.post(/* postdata */, function(resp) {
     if(resp.Succeeded) //close jQuery UI dialog
     else {
         for(var i = 0; i < resp.ValidationMessages; i++) alert(resp.ValidationMessages[i]));
     }
});

You can build your postdata, by quering all input/textarea etc. elements, and saving them into an array, something like (untested):

您可以通过查询所有input / textarea等元素并将它们保存到数组中来构建您的postdata,例如(未经测试):

var data = [];    
$('input').each(function() {
    data.push([ $(this).id, $(this).val() ]);
});

#3


0  

You could use the jQuery form plugin to create an Ajax version of the editing form:

您可以使用jQuery表单插件来创建编辑表单的Ajax版本:

$(".showEditPopup").click(function() {
            function popDialog(htmlResult) {
                $("#EditUserControlDiv").remove();
                $("#container").append(htmlResult);
                $("#container form").ajaxForm(function(result) {
                  // There may be an easier way (like testing for a 
                  // certain string in the result)
                  // to detect the need to "repop"
                  if ($(result).find('form').length) {
                    popDialog(result);
                  } else {
                    $("#EditUserControlDiv").dialog('close'); // or remove
                  }
                });
                $("#container select[multiple]").asmSelect();
                $("#EditUserControlDiv").dialog(
                {
                    height: 675,
                    width: 650,
                    modal: true
                }
                );
            }

        $.post("Applications/ShowEdit",
            { recnum: $(this).parents('tr:first').attr("recnum") },
            function(result) { popDialog(result); }
       );
    }); 

#1


5  

As said

But in this case i want to keep the dialop open and simply show these errors inside the dialog

但在这种情况下,我想保持拨号盘打开,只是在对话框中显示这些错误

Ok.

After openning the dialog, you have to

打开对话框后,您必须这样做

  • hide previous error message
  • 隐藏上一条错误消息

...

open: function(event, ui) {
    $(".error").css("display", "none");
}

After clicking dialog button, you have to

单击对话框按钮后,您必须

  • disable JQuery UI
  • 禁用JQuery UI

  • Show "loading..." image
  • 显示“loading ...”图像

  • Send form

...

$("#loading").css("display", "block");

panel.dialog("disable");

panel.dialog("option", "disabled", true);

After response is loaded (You can use JSON as response), you have to

加载响应后(您可以使用JSON作为响应),您必须

  • Check whether it has errors.
  • 检查是否有错误。

...

// var response plays the role of JSON response

var response = {
    "errors":[
        {
            "property-name":"name",
            "error":"Name is required"
        },
        {
            "property-name":"age",
            "error":""
        }
    ]
};

var hasErrors = false;

for(var i = 0; i < response.errors.length; i++) {
    if(response.errors[i].error != "") {
         hasErrors = true;

         $("#" + response.errors[i]["property-name"] + "-error")
           .text(response.errors[i]["error"])
           .css("display", "block");
    }
}

if(!hasErrors) {
    panel.dialog("close");

    alert("success form!");
} else {
    panel.dialog("enable");

    panel.dialog("option", "disabled", false);
}

Here you can see in Action

在这里你可以看到行动

Notice you have a default behavior. So you can put it inside a external function

请注意,您有默认行为。所以你可以将它放在一个外部函数中

#2


1  

Most convenient:

  • Disable all input elements
  • 禁用所有输入元素

  • Do an Ajax post to the Update function
  • 对Update函数执行Ajax发布

  • Handle the server response in your UI. E.g. closing the jQuery UI form, or showing validation errors.
  • 在UI中处理服务器响应。例如。关闭jQuery UI表单,或显示验证错误。


Change your Update function to return some wrapper object like:

更改您的Update函数以返回一些包装器对象,如:

return new { Succeeded = false, ValidationMessages = new [] { "Incorrect username" } };

$.post(/* postdata */, function(resp) {
     if(resp.Succeeded) //close jQuery UI dialog
     else {
         for(var i = 0; i < resp.ValidationMessages; i++) alert(resp.ValidationMessages[i]));
     }
});

You can build your postdata, by quering all input/textarea etc. elements, and saving them into an array, something like (untested):

您可以通过查询所有input / textarea等元素并将它们保存到数组中来构建您的postdata,例如(未经测试):

var data = [];    
$('input').each(function() {
    data.push([ $(this).id, $(this).val() ]);
});

#3


0  

You could use the jQuery form plugin to create an Ajax version of the editing form:

您可以使用jQuery表单插件来创建编辑表单的Ajax版本:

$(".showEditPopup").click(function() {
            function popDialog(htmlResult) {
                $("#EditUserControlDiv").remove();
                $("#container").append(htmlResult);
                $("#container form").ajaxForm(function(result) {
                  // There may be an easier way (like testing for a 
                  // certain string in the result)
                  // to detect the need to "repop"
                  if ($(result).find('form').length) {
                    popDialog(result);
                  } else {
                    $("#EditUserControlDiv").dialog('close'); // or remove
                  }
                });
                $("#container select[multiple]").asmSelect();
                $("#EditUserControlDiv").dialog(
                {
                    height: 675,
                    width: 650,
                    modal: true
                }
                );
            }

        $.post("Applications/ShowEdit",
            { recnum: $(this).parents('tr:first').attr("recnum") },
            function(result) { popDialog(result); }
       );
    });