在保存按钮点击jQuery的对话框局部视图服务器端验证(Jquery dialog partial

2019-09-01 05:55发布

我有一个显示数据的表。 表的每一行都有编辑按钮。 当点击编辑按钮jQuery的对话框,表格编辑用户信息保存和取消按钮。 形式不过是一个局部视图,按钮是局部视图的一部分。

<button name="button" class="button" id="editCurrentRow" onclick="EditCurrentRow(@item.ID); return false;">

$("#editResult").dialog({
    title: 'Edit Admin',
    autoOpen: false,
    resizable: false,
    height: 500,
    width: 600,
    show: { effect: 'drop', direction: "up" },
    modal: true,
    draggable: true,
    open: function (event, ui) {
        $(this).load('@Url.Action("EditAdmin", "AdminSearchResult")', { id: 1 , isEdit : true }); // pass par from function EditCurrentRow(par) in pacle of 1

    },
    close: function (event, ui) {
        $(this).dialog('close');
    }
});

在单击编辑按钮我得到正确的价值观对话。 如果没有验证错误(服务器端验证)保存按钮工作正常,但一旦有部分页面在新页面中打开验证错误。 取消精品工程。 我的部分观点

@using (Ajax.BeginForm("EditAdmin", "AdminSearchResult", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "editPanel" }))
{
    <div class="editPanel">

        // this is where my html control is 
        <button name="button" value="save" class="button" id="SubmitButton">Save</button>
        &nbsp;
        <button name="button" value="cancel" class="button">Cancel</button>

    </div>
}

我的控制器的ActionResult是

[HttpPost]
    public ActionResult EditAdmin(int id, Administration admin, string button, bool isEdit = false)
    {            
        if (button == "save")
        {
            var errors = admin.Validate(new ValidationContext(admin, null, null));

            if (errors.Count() == 0)
            {                    
                return RedirectToAction("AdminSearchResult", "AdminSearchResult");
            }
            else
            {
                foreach (var error in errors)
                    foreach (var memberName in error.MemberNames)
                        ModelState.AddModelError(memberName, error.ErrorMessage);

                return PartialView("EditAdmin", admin);
            }
        }

        if (button == "cancel")
        {
            return RedirectToAction("AdminSearchResult", "AdminSearchResult");
        }

        return View();
    }

我想,在对话框中的任意按钮点击方法应该是Ajax的指明分数和JSON-化的。 所以我尝试做以下

<script src="../../Scripts/jquery-1.4.4.js" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">  </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {

    $("#SubmitButton").click(function () {

        var id = $('#txtID').val();
        var lName = $('#txtLastName').val();
        var mName = $('#txtMiddleName').val();
        var fName = $('#txtFirstName').val();
        var uName = $('#txtUserName').val();
        var email = $('#txtEmail').val();
        var uRole = $('#ddlUserRoleName').val();
        var active = $('#chkActive').val();

        var admin = {
            ID: id,
            LastName: lName,
            MiddleName: mName,
            FirstName: fName,
            userName: uName,
            emailAddress: email,
            IsActive: active,
            UserRole: uRole
        }

        $.ajax({
            url: '@Url.Action("EditAdmin", "AdminSearchResult")',
            type: 'POST',
            dataType: 'html',
            contentType: "application/json; charset=utf-8",
            data: 'JSON.stringify(admin)',
            success: function (result) {
                alert(result);
                if (result.success) {
                    alert("Success");
                } else {
                    alert("Fail");
                    $('#editPanel').html(result);
                }
            }
        });
        return false;
    });
});   

</script

问题是后添加上$的$就调用(“#提交按钮”)。点击(函数()按钮少了点点击时做任何事情。我希望它发生时没有服务器和客户端验证错误保存,如果有应显示在对话框中的错误信息。

此外,在我的web配置我有验证正确的设置

<appSettings>
    <add key="ClientValidationEnabled" value="true"/> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 
</appSettings>

谢谢

Answer 1:

你应该尝试unobstrusive客户端验证实例

JQuery的

$('#BTN').click(function () {
    var $formContainer = $('#formContainer');
    var url = $formContainer.attr('data-url');
    $formContainer.load(url, function () {
        var $form = $('#myForm');
        $.validator.unobtrusive.parse($form);
        $form.submit(function () {
            var $form = $(this);
            if ($form.valid()) {
                $.ajax({
                    url: url,
                    async: true,
                    type: 'POST',
                    data: JSON.stringify("Your Object or parameter"),
                    beforeSend: function (xhr, opts) {
                    },
                    contentType: 'application/json; charset=utf-8',
                    complete: function () { },
                    success: function (data) {
                        $form.html(data);
                        $form.removeData('validator');
                        $form.removeData('unobtrusiveValidation');
                        $.validator.unobtrusive.parse($form);
                    }
                });
            }
            return false;
        });
    });
    return false;
});

视图

<div id="formContainer" data-url="@Url.Action("ActionName", "ControllerName", 
                                             new { area = "Area Name" })"></div>
<input id="BTN" type="button" value="Button" />

模型

public class SampleModule
{
    [Required]
    public String MyName { get; set; }
}

部分景观

@using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post, 
                       new { id = "myForm" }))
{
    @Html.LabelFor(i => i.MyName)
    @Html.TextBoxFor(i => i.MyName)
    @Html.ValidationMessageFor(i => i.MyName)
    <p id="getDateTimeString"></p>
   <input type="button" value="Button" />        
}

参考

<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js" type="text/javascript">
</script>


Answer 2:

嗨,无需编写任何Jscript中我们可以我们内置unobstrusive功能。 如下。

模型

    Public class Model{[Required(ErrorMessage = "Required.")]
   [Range(0, int.MaxValue, ErrorMessage = "Please enter a Number")]
   public int NumberOfPosters { get; set; }}

部分景观

    @Html.TextBoxFor(model => model.NumberOfPosters, new { style="width:150px;"})
     @Html.ValidationMessageFor(model => model.NumberOfPosters)



文章来源: Jquery dialog partial view server side validation on Save button click