3

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

1
  • Can you open this on chrome, open chrome dev tools and paste the message if you are seeing anything on console? Commented Apr 26, 2013 at 21:42

2 Answers 2

5

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

5 Comments

Pankaj thanks for the Answer. All these changes should be partial view right?
what is var $form = $('#myForm'); whose id is myform
I am new to mvc so excuse my not so intelligent questions. So the partial view will look like this @using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post, new { id = "myForm" })){<div id="formContainer" data-url="@Url.Action("ActionName", "ControllerName", new { area = "Area Name" })"> @Html.LabelFor(i => i.MyName) @Html.TextBoxFor(i => i.MyName) @Html.ValidationMessageFor(i => i.MyName) <p id="getDateTimeString"></p> <input type="submit" value="Click here" /> </div> }
I did all you asked. Well the button just does not respond. <div id="formContainer" data-url="@Url.Action("ActionName", "ControllerName", new { area = "Area Name" })"></div> is your div for dialog right.
tried both. Not working. Will try again during weekend if not i ll leave a comment. Thanks a lot of all your help. Have a good weekend.
1

Hi without writing any Jscript we can us inbuilt unobstrusive features. as below.

Model

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

Partial View

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

Example Imge

1 Comment

this wont work if your add button uses default submit action which does a postback.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.