簡體   English   中英

重新初始化不顯眼的 jquery 驗證

[英]Reinitialize unobstrusive jquery validation

我已經通過 ajax 重新綁定視圖模型,因為我不喜歡默認功能模式彈出窗口,因為我忘記了我正在關注的教程鏈接,這是我的一些代碼

數據表代碼

$(document).ready(function () {
    $("#btnNew").text("New");
    $('#grid-src').hide();

    $('#btnToggleSrc').click(function () {
        $('#grid-src').toggle();
    });

    $("#btnNew").on("click", function (e) {
        $.ajax({
            type: "POST",
            url: '@Url.Action("Edit", "Roles", new { area = "PM" })',
            dataType: 'json',
            data: { id: 0 },
            success: function (obj) {                    
                switch (obj.ResponseMsg.MsgType) {
                    case 'SUCCESS':
                        var roles = obj.Data;

                        $.ajax({
                            type: "POST",
                            url: '@Url.Action("LoadEdit", "Roles", new { area = "PM" })',
                            dataType: 'json',
                            data: { role: roles },
                            sucecss: function (obj) {

                            },
                            complete: function () {
                                $('#modal-title').text('New Role');
                                $('#edit-form').modal('show');
                            }
                        });
                        break;
                    case 'WARNING':
                        toastr.warning(obj.ResponseMsg.MsgDesc);
                        break;
                    case 'ERROR':
                        toastr.error(obj.ResponseMsg.MsgDesc);
                        break;
                }
            }
        });
    });

    $('#table-container').on('click', 'a.btn-edit', function (e) {
        var param = parseInt(this.id.replace('edit-', ''));
        $.post('@Url.Action("Edit", "Roles", new { area = "PM" })', { id: param })
            .done(function (obj) {
                switch (obj.ResponseMsg.MsgType) {
                    case 'SUCCESS':
                        var role = obj.Data;

                        $.post('@Url.Action("LoadEdit", "Roles", new { area = "PM" })', { role: role })
                            .done(function (obj) {
                                debugger;
                                $('#edit-form-partial').html(obj);
                                //$.validator = $('#frmSubmit').validate(
                                //{
                                //    ignore: ":hidden"
                                //});
                                $('#modal-title').text('Edit Role');
                                $('#edit-form').modal('show');
                            });
                        break;
                    case 'WARNING':
                        toastr.warning(obj.ResponseMsg.MsgDesc);
                        break;
                    case 'ERROR':
                        toastr.error(obj.ResponseMsg.MsgDesc);
                        break;
                }         
            });
    });
    var url = "@Url.Action("Read", "Roles", new { area = "PM" })"

    var oTable = $('#table').dataTable({
                    "processing": false,
                    "serverSide": true,
                    "orderMulti": false,
                    "sScrollY": ($(window).height() - 300),
                    "sScrollYInner": "100%",
                    "sheight": "425px",
                    "pageLength": 10,
                    "dom": '<"top"i>rt<"bottom"lp><"clear">',
                    "ajax": {
                        "url": url,
                        "type": "POST",
                        "datatype": "json",
                        "error": function (xhr, ajaxOptions, thrownError) {
                            alert(thrownError);
                        }
                    },
                    "columns": [
                        { "data": "ID", "name": "ID", "autowidth": true, "visible": false },
                        { "data": "RoleName", "name": "RoleName", "autowidth": true },
                        { "data": "CreatedBy", "name": "CreatedBy", "autowidth": true, "sorting": false },
                        {
                            "data": "CreatedTime", "name": "CreatedTime", "autowidth": true, "render": function (jsonDate) {
                                return generateDate(jsonDate);
                            },
                            "sorting": false
                        },
                        { "data": "ModifiedBy", "name": "ModifiedBy", "autowidth": true, "sorting": false },
                        {
                            "data": "ModifiedTime", "name": "ModifiedTime", "autowidth": true, "render": function (jsonDate) {
                                return generateDate(jsonDate);
                            },
                            "sorting": false
                        },
                        {
                            "data": "ID", "width": "50px", "render": function (data) {
                                return '<a class="btn-edit" href="javascript:void(0)" id="edit-' + data + '" style="cursor: pointer">Edit</a>';
                            },
                            "sorting": false
                        },
                        {
                            "data": "ID", "width": "50px", "render": function (data) {
                                return '<a class="btn-delete" href="javascript:void(0) id="delete-' + data + '" style="cursor: pointer">Delete</a>';
                            },
                            "sorting": false
                        }
                    ]
    });

部分編輯表單

@myProject.MyViewModel
@{ 
    Html.EnableClientValidation(true);
}

@using (Ajax.BeginForm("Save", "Roles", new { area = "PM" }, new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    OnSuccess = "successSave",
    OnFailure = "failSave"
},
new { @id = "frmSubmit" }))
{
    @Html.AntiForgeryToken()
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"><span id="modal-title"></span></h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-4">
                        @Html.HiddenFor(model => model.ID, new { @id = "roleFlag" })
                        @Html.LabelFor(model => model.RoleName)
                    </div>
                    <div class="col-8">
                        @Html.TextBoxFor(model => model.RoleName, new { @style = "width:210px", @id = "tbRoleName", @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.RoleName, "", new { @class = "text-danger", style = "font-size: 12px;", @id = "val-role" })
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <div class="row right">
                    <div class="col-2">
                        <button type="submit" class="btn btn-primary">Save</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
}

和 controller 代碼

[HttpPost]
    public ActionResult Edit (long id)
    {
        var result = new JsonResult();

        try
        {
            BPPMRoles objBP = new BPPMRoles();
            var role = objBP.Find(id);
            if (objBP.MsgCode != 0)
            {
                result = new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        ResponseMsg = new
                        {
                            MsgCode = objBP.MsgCode,
                            MsgType = "ERROR",
                            MsgDesc = "There's something wrong, please contact us about this issue (Error Code = " + objBP.MsgCode + ")"
                        },
                        Data = new myViewModel()
                    }
                };
                return result;
            }

            var mapper = mapConfig.CreateMapper();
            var roles = mapper.Map<myModel, myViewMode>(role);

            result = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    ResponseMsg = new
                    {
                        MsgCode = 0,
                        MsgType = "SUCCESS",
                        MsgDesc = string.Empty
                    },
                    Data = roles ?? new myViewModel()
                }
            };

            return result;
        }
        catch (Exception err)
        {
            result = new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    ResponseMsg = new
                    {
                        MsgCode = 10,
                        MsgType = "ERROR",
                        MsgDesc = "There's something wrong, please contact us about this issue (Error Code = " + 10 + ")"
                    },
                    Data = new myViewModel()
                }
            };

            return result;
        }
    }

    [HttpPost]
    public ActionResult LoadEdit(myViewModel role)
    {
        return PartialView("_Edit", role);
    }

視圖 model

public class myViewModel
{
    public long ID { get; set; }

    [Display(Name = "Role")]
    [Required(ErrorMessage = "Role must not be empty!", AllowEmptyStrings = false)]
    [MaxLength(150)]
    public string RoleName { get; set; }

    public string CreatedBy { get; set; }
    public DateTime CreatedTime { get; set; }
    public string ModifiedBy { get; set; }
    public DateTime? ModifiedTime { get; set; }
}

問題是,重新綁定部分視圖后,強制驗證始終為真,重新綁定后所需的驗證不起作用

編輯:我試過 .validate() 和 .valid()

它總是返回 true,即使文本框為空

我有一個項目加載 json 數據並用它填充幾個 forms。

方法一我設法通過做 3 件事讓它發揮作用。

1-在填充字段之前重置表單,如下所示:

$("#MyFormId").trigger("reset");

2-使用 javascript 填充字段

 $("#MyFieldName").val(myValueGoesHere);

3-在所有文本字段上觸發更改事件,如下所示:

 $("#MyFieldName").trigger("change");

請注意,2 和 3 可以像這樣在一行中實現:

 $("#MyFieldName").val(myValueGoesHere).trigger("change");

方式二

如果您真的需要動態加載表單的“html 內容”而不僅僅是數據...

你可以試試這個:

function rebindvalidators() {
var $form = $("#MyFormId");
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse($form);
$form.validate($form.data("unobtrusiveValidation").options);

}

從完成的處理程序中調用 function,如下所示:

.done(function (obj) {
                                debugger;
                                $('#edit-form-partial').html(obj);
                                rebindvalidators();//rebind your validators after loading the html.
                                //$.validator = $('#frmSubmit').validate(
                                //{
                                //    ignore: ":hidden"
                                //});
                                $('#modal-title').text('Edit Role');
                                $('#edit-form').modal('show');
                            });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM