Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

asp.net mvc - Jquery dialog partial view server side validation on Save button click

I have a table that displays data. Each row of table has Edit button. When edit button is clicked a jquery dialog appears with Form for editing the user info and save and cancel button . The form is nothing but a partial view buttons are part of partial view.

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

on clicking edit button I get dialog with proper values. When there is no validation error(Server side validation) the save button works fine but once there is a validation error the partial page opens in a new page. the Cancel works fine. My partial view

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

my controller actionResult is

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

I figured that any button click method in dialog should be a ajax-ified and json-ized. So i tried doing the following

<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

The issue is the after adding the $.ajax call on $("#SubmitButton").click(function () the button just does do anything when clicked. I want it to save when no server and client side validation error occurs and if there is the error messages should be displayed in the dialog.

Also in my web config I have proper setting for validation

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

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should try unobstrusive Client side Validation Example

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

View

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

Model

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

Partial View

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

References

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...