3

我有一个显示数据的表格。每行表格都有编辑按钮。单击编辑按钮时,会出现一个带有表单的 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

问题是在 $("#SubmitButton").click(function () 上添加 $.ajax 调用后,该按钮在单击时会执行任何操作。我希望它在没有发生服务器和客户端验证错误时保存,如果有错误消息应该显示在对话框中。

同样在我的网络配置中,我有适当的验证设置

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

谢谢

4

2 回答 2

5

您应该尝试不显眼的客户端验证示例

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>
于 2013-04-26T21:42:59.283 回答
0

嗨,无需编写任何 Jscript,我们就可以内置不显眼的功能。如下。

模型

    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)

示例图片

于 2016-02-21T07:47:16.663 回答