0

I've rebinding viewmodel via ajax because of I don't like the default feature modal popup, since I forgot which tutorial link I'm following, here's some of my code

The datatable code

$(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
                        }
                    ]
    });

The edit form partial

@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>
}

and the controller code

[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);
    }

the view 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; }
}

the problem is, after rebinding the partialview, the obstrusive validation is always true, the required validation not working after rebinding

Edit: I've tried .validate() and .valid()

It's always returns true, even when the textbox is empty

1 Answer 1

1

I got one of my projects that loads json data and populates several forms with it.

Way Number One I managed to make it work by doing 3 things.

1- reset the form before populating the fields like this:

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

2- Populate the fields using javascript

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

3- Trigger the change event on all text fields like this:

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

Notice that 2 and 3 can be achieved in a single line like this:

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

Way Number Two

If you really need to load the "html content" of the form dynamically rather than just the data...

You can try this:

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

}

Calling that function from your done handler like this:

.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');
                            });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.