ASP.NET MVC jquery.UI对话框 - 如何在服务器上验证对话框的输入并返回错误?

时间:2022-11-30 17:28:33

I am using jQuery1.4.2, ASP.NET MVC 2 and jQuery.UI-1.8.

我使用的是jQuery1.4.2,ASP.NET MVC 2和jQuery.UI-1.8。

I am creating a data input dialog which works OK when all the data is valid, but I want to validate the input data on the server and return an error to the dialog describing the error and I am not quite sure how to do that and keep the dialog open. The dialog is opened when a link is clicked. The solution may be to try to bypass more of the MVC framework's default binding that handles the submit button clicks and creates the expected ProfilePermission object and calls the Controller's AddPermission POST Action method, but I was hoping there may be an easier way without having to write more jquery/javascript code to handle the button clicks and pass the data to/from the server.

我正在创建一个数据输入对话框,当所有数据都有效时工作正常,但我想验证服务器上的输入数据并将错误返回到描述错误的对话框,我不太清楚如何做到这一点并保持对话框打开。单击链接时将打开该对话框。解决方案可能是试图绕过更多的MVC框架的默认绑定来处理提交按钮点击并创建预期的ProfilePermission对象并调用Controller的AddPermission POST Action方法,但我希望可能有一种更简单的方法而不必编写更多jquery / javascript代码来处理按钮点击并将数据传入/传出服务器。

My script code looks like

我的脚本代码看起来像

$("#dialog").dialog({ modal: true,
    position: ['center', 180],
    width: 500,
    height: 130,
    autoOpen: false
});

$(".addPermissionDialog").click(function (event) {
    event.preventDefault();
    $("#dialog").dialog('open');
    return false;
});

My View

<div id="dialog" title="Add Permission">
<%: Html.ValidationSummary("") %>
<% using (Html.BeginForm("AddPermission", "Profile"))
{ %>
    <%: Html.Hidden("PersonId") %>
    <%: Html.Hidden("ProfileId") %>
    <div class="editor-label">
        <label for="PersonName">User Name:</label>
        <%: Html.TextBox("PersonName")%>
        <label for="PermissionType">Permission:</label>
        <select name="PermissionTypeId" id="PermissionTypeId" >
            <option value="2">Edit</option>
            <option value="3">View</option>
        </select>
    </div>
    <br />
    <p>
    <input type="submit" name="saveButton" value="Add Permission" />
    <input type="submit" id="cancelButton" name="cancelButton" value="Cancel" />
    <script type="text/javascript">
        document.getElementById("cancelButton").disableValidation = true;
    </script>
    </p>
<% } %>
</div>
<br />
<p>
    <%: Html.ActionLink("Add Permission", "AddPermission", new { profileId = Model.First().ProfileId }, new { @class = "addPermissionDialog" })%>
</p>

My Controller action

我的控制器动作

    [AcceptVerbs("Post")]
    [HandleError]
    public ActionResult AddPermission(string cancelButton, ProfilePermission profilePermission)
    {
        ViewData["Controller"] = controllerName;
        ViewData["CurrentCategory"] = "AddPermission";
        ViewData["ProfileId"] = profilePermission.ProfileId;

        PermissionTypes permission = repository.GetAccessRights(profilePermission.ProfileId);
        if (permission == PermissionTypes.View || permission == PermissionTypes.None)
        {
            ViewData["Message"] = "You do not have access rights (Edit or Owner permissions) to this profile";
            return View("Error");
        }

        // If cancel return to previous page
        if (cancelButton != null)
        {
            return RedirectToAction("ManagePermissions", new { profileId = profilePermission.ProfileId });
        }

        if (ModelState.IsValid)
        {
            repository.SavePermission(profilePermission);

            return RedirectToAction("ManagePermissions", new { profileId = profilePermission.ProfileId });
        }

        // IF YOU GET HERE THERE WAS AN ERROR
        return PartialView(profilePermission); // The desire is to redisplay the dialog with error message
    }

LATER EDIT I was hoping for a mechanism to return an error to the dialog using MVC's plumbing, I eventually broke down and added a save button via the jquery.ui.dialog API and handled the issue that way. I removed the buttons from the .aspx page. I returned return new EmptyResult(); from the controller's actions if everything worked OK and if there was an error Response.StatusCode = (int)HttpStatusCode.BadRequest; return Content(errorMessage, MediaTypeNames.Text.Plain);

稍后编辑我希望有一种机制使用MVC的管道将错误返回到对话框,我最终崩溃并通过jquery.ui.dialog API添加了一个保存按钮并以这种方式处理问题。我从.aspx页面中删除了按钮。我返回了返回new EmptyResult();从控制器的操作,如果一切正常,如果有错误Response.StatusCode =(int)HttpStatusCode.BadRequest; return Content(errorMessage,MediaTypeNames.Text.Plain);

    // To add a button and bypass more of MVC plumbing
    buttons: {
        "Save": function () {
            var dlg = $(this);
            $.ajax({
                url: "/Profile/AddPermission",
                type: 'POST',
                data: {
                    PersonId: $("#PersonId").val(),
                    ProfileId: $("#ProfileId").val(),
                    PermissionTypeId: $("#PermissionTypeId").val(),
                    PersonName: $("#PersonName").val()
                },
                success: function (data) {
                    dlg.dialog('close');
                },
                error: function (data) {
                    alert(data.responseText);
                }
            });
        }
    }

2 个解决方案

#1


1  

I was doing this kind of stuff using jquery.form and jquery dialog; in the post action if everything is good you return Content("OK") if not you return the PartialView() (that contains the modelstate errors) after in the function that handles the successful post response you check if it is "OK" close the dialog if not you set the $("#yourDialogDiv").html(responseHtmlThatYouGotFromTheServer)

我正在使用jquery.form和jquery对话框来做这种事情;在post动作中如果一切都很好你返回Content(“OK”)如果不是你返回PartialView()(包含模型状态错误)之后在处理成功的post响应的函数中你检查它是否“OK”关闭对话框,如果没有你设置$(“#yourDialogDiv”)。html(responseHtmlThatYouGotFromTheServer)

#2


0  

I would suggest changing the input type submit to a normal button and making an Ajax call on click of the button, to ensure that the dialog is not closed. Send data to the server using JsonValueProviderFactory from the MVC2 futures library based on Phils post. If the validation fails trap the error in the ajax error: option. If data is valid close the dialog from the Ajax complete: option. Hope this helps.

我建议将输入类型提交更改为普通按钮,并在单击按钮时进行Ajax调用,以确保对话框未关闭。使用基于Phils帖子的MVC2期货库中的JsonValueProviderFactory将数据发送到服务器。如果验证失败,则在ajax error:选项中捕获错误。如果数据有效,请关闭Ajax complete:选项中的对话框。希望这可以帮助。

#1


1  

I was doing this kind of stuff using jquery.form and jquery dialog; in the post action if everything is good you return Content("OK") if not you return the PartialView() (that contains the modelstate errors) after in the function that handles the successful post response you check if it is "OK" close the dialog if not you set the $("#yourDialogDiv").html(responseHtmlThatYouGotFromTheServer)

我正在使用jquery.form和jquery对话框来做这种事情;在post动作中如果一切都很好你返回Content(“OK”)如果不是你返回PartialView()(包含模型状态错误)之后在处理成功的post响应的函数中你检查它是否“OK”关闭对话框,如果没有你设置$(“#yourDialogDiv”)。html(responseHtmlThatYouGotFromTheServer)

#2


0  

I would suggest changing the input type submit to a normal button and making an Ajax call on click of the button, to ensure that the dialog is not closed. Send data to the server using JsonValueProviderFactory from the MVC2 futures library based on Phils post. If the validation fails trap the error in the ajax error: option. If data is valid close the dialog from the Ajax complete: option. Hope this helps.

我建议将输入类型提交更改为普通按钮,并在单击按钮时进行Ajax调用,以确保对话框未关闭。使用基于Phils帖子的MVC2期货库中的JsonValueProviderFactory将数据发送到服务器。如果验证失败,则在ajax error:选项中捕获错误。如果数据有效,请关闭Ajax complete:选项中的对话框。希望这可以帮助。