[RESOLVED]How to Redirect page to partial view on update click?

Hello Everyone, 

    I am facing problem with Ajax.BeginForm. Please help me. I am having profile view. Here user can update his details(eg. present address, permanent address, email, etc). for this i used Ajax.BeginForm. But the thing is page should not be refreshed when
updating profile. I used partial view here.

On update click, page is redirected to json result. I am posting my code also. checkout once & let me know what’s the mistake here. 

View code : 

<div class="col-sm-10 no-padding" id="hello">

            @using (Ajax.BeginForm("UpdateProfile", "Profile", new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnSuccess = "updateSuccess(data)" },
    new { @id = "updateUserForm" }))
            {
                @Html.ValidationSummary(true)

                <div class="profile-my-IC col-xs-12">
                    <div class="col-xs-2">Name</div>
                    <div class="col-xs-4">@Html.DisplayTextFor(m => m.FirstName)</div>
                    <div class="col-xs-2">Gender</div>
                    <div class="col-xs-4">
                        @if (Model.EmpGender == true)
                        {@Html.Label("Male")}
                        else
                        {@Html.Label("Female")}
                    </div>
                </div>
                <div class="profile-my-IC col-xs-12">
                    <div class="col-xs-2">DOB:</div>
                    <div class="col-xs-4">@Html.Label(Model.DOB.Date.ToString(" MMM dd yyyy"))</div>

                    <div class="col-xs-2">DOJ:</div>
                    <div class="col-xs-4">@Html.Label(Model.DOJ.Date.ToString(" MMM dd yyyy"))</div>
                </div>
                <div class="profile-my-IC col-xs-12">

                    <div class="col-xs-6 no-padding">
                        <div class="col-xs-12">
                            Present Address : <i class="fa fa-pencil" id="add"></i>
                        </div>
                        <div class="col-xs-12">
                            @Html.DisplayFor(m => m.Address1, new { id = "upaddress" })
                        </div>
                        <div id="at">
                            @Html.EditorFor(m => m.Address1)
                            @Html.ValidationMessageFor(m => m.Address1)
                            <button type="submit" class="btn btn-primary btn-xs">Update</button>
                            <button id="PCancel" type="button" class="btn btn-primary btn-xs">Cancel</button>
                        </div>
                    </div>

                    <div class="col-sm-6 no-padding">
                        <div class="col-xs-12">
                            Permanent Address:
                        </div>
                        <div class="col-xs-12 editor-field ">
                            @Html.DisplayFor(m => m.Address2)
                        </div>
                    </div>
                </div>
                <div class="profile-my-IC">
                    <div class="editor-field col-sm-6">
                        <div class="col-xs-12 no-padding">
                            Personal Email : <i id="email" class="fa fa-pencil" style="cursor: pointer"></i>
                        </div>
                        <div class="col-xs-12 no-padding" id="eml">@Html.DisplayFor(m => m.EMail)</div>


                        <div id="emt" class="col-sm-6 ">
                            <div class="editor-field col-sm-12 ">
                                @Html.EditorFor(model => model.EMail)
                                @Html.ValidationMessageFor(model => model.EMail)

                                <button type="submit" class="btn btn-primary btn-xs">Update</button>
                                <button id="EMCancel" type="button" class="btn btn-primary btn-xs">Cancel</button>
                            </div>
                        </div>
                    </div>
                    <div class="editor-field col-sm-6">
                        Work Email : <i id="extn" class="fa fa-pencil" style="cursor: pointer"></i> @Html.DisplayFor(m => m.EmpEmailId)
                    </div>
                </div>
                <div class="profile-my-IC">
                    <div class=" col-sm-6">
                        <span class="col-sm-6"> Office Extension Number :</span>

                        <span id="el" class="col-sm-4">@Html.DisplayFor(m => m.EmpOfficeExt, new { id = "KAM" }) </span>
                        <div id="et" class="col-sm-6">
                            <div class="editor-field col-sm-6">
                                <span class="col-sm-6 "> @Html.EditorFor(m => m.EmpOfficeExt)</span>
                                @Html.ValidationMessageFor(m => m.EmpOfficeExt)
                                @Html.HiddenFor(m => m.filemanager.FileName)
                                <button type="submit" class="btn btn-primary btn-xs">Update</button>
                                <button id="ECancel" type="button" class="btn btn-primary  btn-xs">Cancel</button>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        Landline :@Html.DisplayFor(m => m.HomePhone)
                    </div>
                </div>
                <div class="row-sm-12">
                    <div class="editor-field col-sm-6 ">
                        <span class="col-sm-6 "> Mobile :</span>
                        <span id="cl" class="col-sm-6 ">@Html.DisplayFor(m => m.CellPhone)<i id="cell" class="fa fa-pencil" style="cursor: pointer"></i></span>
                        <div id="ct">
                            @Html.EditorFor(m => m.CellPhone, new { id = "NumberTest" })
                            @Html.ValidationMessageFor(m => m.CellPhone)
                            <button type="submit" class="btn btn-primary">Update</button>
                            <button id="CCancel" type="button" class="btn btn-primary">Cancel</button>
                        </div>
                    </div>
                </div>
                <div class="profile-my-IC">
                    <div class="col-sm-6">
                        Shift :@if (Model.ShiftNo == 1)
                        {@Html.Label("Day Shift")}
                        else if (Model.ShiftNo == 2)
                        {@Html.Label("Night Shift")}
                                                @*<span class="col-sm-6">*@

                                                @*</span>*@
                                            </div>
                                            <div class="col-sm-6">
                                                Department : @Html.DisplayFor(m => m.Department)
                                            </div>
                                        </div>
                                        @Html.HiddenFor(m => m.StaffID)
                                        @Html.HiddenFor(m => m.UserID)
                                        @Html.HiddenFor(m => m.DOB)
                                        @Html.HiddenFor(m => m.DOJ)
                                        @Html.HiddenFor(m => m.ShiftNo)
                                        @Html.HiddenFor(m => m.FirstName)
                                        @Html.HiddenFor(m => m.CellPhone)
                                        @Html.HiddenFor(m => m.HomePhone)
                                        @Html.HiddenFor(m => m.EMail)
                                        @Html.HiddenFor(m => m.EmpOfficeExt)
                                        @Html.HiddenFor(m => m.EmpEmailId)
                                        @Html.HiddenFor(m => m.EmpImgID)
            }
        </div>

Javascript function : 

 function updateSuccess(data) {

        debugger

        //    $('#el').val(data.EmpOfficeExt).replace(/"/g, "");
        //    $('#et').hide();
        //    $('#el').show();
        //    $('#extn').show();
        //}

        $.ajax({
            url: '@(Url.Action("Index", "Profile"))',
            //url: "/Profile/Index/",
            type: "GET",
            //dataType: "json",
            //contentType: "application/json; charset=utf-8",
            success: function (data) {

                $('#Profile').empty();
                $('#Profile').append(data);
            },
            error: function (xhr, status, error) { alert(error); }
        });
    }


controller code : 
[HttpPost]//update image
        [Authorize]
         public JsonResult UpdateProfile(Staff staffModel, HttpPostedFileBase profileFile)
        //public ActionResult UpdateProfile(Staff staffModel, HttpPostedFileBase profileFile)
        {
            try
            {
                if (Request.IsAjaxRequest() == true)
                {

                }
                // ajax request handled


                if (profileFile != null)
                {

                    DateTime currentDT = System.DateTime.Now;
                    var prsntdate = currentDT.ToString("d").Replace('/', '.');
                    var prsnttime = currentDT.ToString("HH.mm.ss.ffff");
                    var empfileid = (prsntdate + prsnttime).Replace(".", "");
                    string profileFName = System.IO.Path.GetFileName(profileFile.FileName).Split(new[] { '.' }, 2)[0].Trim() + String.Format("{0:dmmyyhhMMss}", currentDT).Trim() + ".Jpg";
                    profileFile.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["FilePath"].ToString() + "Employee Photos/" + profileFName));
                    // profileFile.SaveAs(Server.MapPath("~/FileManager/Employee Photos/" + profileFName));
                    staffModel.filemanager.EventID = null;
                    staffModel.filemanager.FilePath = "Employee Photos/" + profileFName;
                    staffModel.filemanager.FileName = System.IO.Path.GetFileName(profileFile.FileName);
                    staffModel.filemanager.FileID = empfileid;
                    staffModel.EmpImgID = staffModel.filemanager.FileID;
                    profilehlpr.UpdateStaffDetails(staffModel);
                    return Json(staffModel, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    profilehlpr.UpdateStaffDetail(staffModel);
                    return Json(staffModel, JsonRequestBehavior.AllowGet);
                    //return RedirectToAction("Index");
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Thanks in Advance

Satish Chandragiri

Do not use input type submit instead use input type=button

Hi Srinu, 

     Thanks for u’r reply. I tried with input type = button. Even though no result …. 

check if this can help you

controller, returning just the status instead of complete model

[HttpPost]//update image
        [Authorize]
        public JsonResult UpdateProfile(Staff staffModel, HttpPostedFileBase profileFile)
        //public ActionResult UpdateProfile(Staff staffModel, HttpPostedFileBase profileFile)
        {
            try
            {
                if (Request.IsAjaxRequest() == true)
                {

                }
                // ajax request handled


                if (profileFile != null)
                {

                    DateTime currentDT = System.DateTime.Now;
                    var prsntdate = currentDT.ToString("d").Replace('/', '.');
                    var prsnttime = currentDT.ToString("HH.mm.ss.ffff");
                    var empfileid = (prsntdate + prsnttime).Replace(".", "");
                    string profileFName = System.IO.Path.GetFileName(profileFile.FileName).Split(new[] { '.' }, 2)[0].Trim() + String.Format("{0:dmmyyhhMMss}", currentDT).Trim() + ".Jpg";
                    profileFile.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["FilePath"].ToString() + "Employee Photos/" + profileFName));
                    // profileFile.SaveAs(Server.MapPath("~/FileManager/Employee Photos/" + profileFName));
                    staffModel.filemanager.EventID = null;
                    staffModel.filemanager.FilePath = "Employee Photos/" + profileFName;
                    staffModel.filemanager.FileName = System.IO.Path.GetFileName(profileFile.FileName);
                    staffModel.filemanager.FileID = empfileid;
                    staffModel.EmpImgID = staffModel.filemanager.FileID;
                    profilehlpr.UpdateStaffDetails(staffModel);
                    return Json(staffModel, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    profilehlpr.UpdateStaffDetail(staffModel);
                    return Json(new { status=true}, JsonRequestBehavior.AllowGet);
                    //return RedirectToAction("Index");
                }

            }
            catch (Exception ex)
            {

                return Json(new { status = false }, JsonRequestBehavior.AllowGet);
                throw ex;
            }
        }

view

<div class="col-sm-10 no-padding" id="hello">

    @using (Ajax.BeginForm("UpdateProfile", "Profile", new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST" },
    new { @id = "updateUserForm" }))
    {
        @Html.ValidationSummary(true)

        <div class="profile-my-IC col-xs-12">
            <div class="col-xs-2">Name</div>
            <div class="col-xs-4">@Html.DisplayTextFor(m => m.FirstName)</div>
            <div class="col-xs-2">Gender</div>
            <div class="col-xs-4">
                @if (Model.EmpGender == true)
                {@Html.Label("Male")}
                else
                {@Html.Label("Female")}
            </div>
        </div>
        <div class="profile-my-IC col-xs-12">
            <div class="col-xs-2">DOB:</div>
            <div class="col-xs-4">@Html.Label(Model.DOB.Date.ToString(" MMM dd yyyy"))</div>

            <div class="col-xs-2">DOJ:</div>
            <div class="col-xs-4">@Html.Label(Model.DOJ.Date.ToString(" MMM dd yyyy"))</div>
        </div>
        <div class="profile-my-IC col-xs-12">

            <div class="col-xs-6 no-padding">
                <div class="col-xs-12">
                    Present Address : <i class="fa fa-pencil" id="add"></i>
                </div>
                <div class="col-xs-12">
                    @Html.DisplayFor(m => m.Address1, new { id = "upaddress" })
                </div>
                <div id="at">
                    @Html.EditorFor(m => m.Address1)
                    @Html.ValidationMessageFor(m => m.Address1)
                    <button type="submit" class="btn btn-primary btn-xs" onclick="updateSuccess()">Update</button>
                    <button id="PCancel" type="button" class="btn btn-primary btn-xs">Cancel</button>
                </div>
            </div>

            <div class="col-sm-6 no-padding">
                <div class="col-xs-12">
                    Permanent Address:
                </div>
                <div class="col-xs-12 editor-field ">
                    @Html.DisplayFor(m => m.Address2)
                </div>
            </div>
        </div>
        <div class="profile-my-IC">
            <div class="editor-field col-sm-6">
                <div class="col-xs-12 no-padding">
                    Personal Email : <i id="email" class="fa fa-pencil" style="cursor: pointer"></i>
                </div>
                <div class="col-xs-12 no-padding" id="eml">@Html.DisplayFor(m => m.EMail)</div>


                <div id="emt" class="col-sm-6 ">
                    <div class="editor-field col-sm-12 ">
                        @Html.EditorFor(model => model.EMail)
                        @Html.ValidationMessageFor(model => model.EMail)

                        <button type="submit" class="btn btn-primary btn-xs" onclick="updateSuccess()">Update</button>
                        <button id="EMCancel" type="button" class="btn btn-primary btn-xs">Cancel</button>
                    </div>
                </div>
            </div>
            <div class="editor-field col-sm-6">
                Work Email : <i id="extn" class="fa fa-pencil" style="cursor: pointer"></i> @Html.DisplayFor(m => m.EmpEmailId)
            </div>
        </div>
        <div class="profile-my-IC">
            <div class=" col-sm-6">
                <span class="col-sm-6"> Office Extension Number :</span>

                <span id="el" class="col-sm-4">@Html.DisplayFor(m => m.EmpOfficeExt, new { id = "KAM" }) </span>
                <div id="et" class="col-sm-6">
                    <div class="editor-field col-sm-6">
                        <span class="col-sm-6 "> @Html.EditorFor(m => m.EmpOfficeExt)</span>
                        @Html.ValidationMessageFor(m => m.EmpOfficeExt)
                        @Html.HiddenFor(m => m.filemanager.FileName)
                        <button type="submit" class="btn btn-primary btn-xs" onclick="updateSuccess()">Update</button>
                        <button id="ECancel" type="button" class="btn btn-primary  btn-xs">Cancel</button>
                    </div>
                </div>
            </div>
            <div class="col-sm-6">
                Landline :@Html.DisplayFor(m => m.HomePhone)
            </div>
        </div>
        <div class="row-sm-12">
            <div class="editor-field col-sm-6 ">
                <span class="col-sm-6 "> Mobile :</span>
                <span id="cl" class="col-sm-6 ">@Html.DisplayFor(m => m.CellPhone)<i id="cell" class="fa fa-pencil" style="cursor: pointer"></i></span>
                <div id="ct">
                    @Html.EditorFor(m => m.CellPhone, new { id = "NumberTest" })
                    @Html.ValidationMessageFor(m => m.CellPhone)
                    <button type="submit" class="btn btn-primary" onclick="updateSuccess()">Update</button>
                    <button id="CCancel" type="button" class="btn btn-primary">Cancel</button>
                </div>
            </div>
        </div>
        <div class="profile-my-IC">
            <div class="col-sm-6">
                Shift :@if (Model.ShiftNo == 1)
                {@Html.Label("Day Shift")}
                else if (Model.ShiftNo == 2)
                {@Html.Label("Night Shift")}
                                        @*<span class="col-sm-6">*@

                                        @*</span>*@
                                    </div>
                                    <div class="col-sm-6">
                                        Department : @Html.DisplayFor(m => m.Department)
                                    </div>
                                </div>
                                @Html.HiddenFor(m => m.StaffID)
                                @Html.HiddenFor(m => m.UserID)
                                @Html.HiddenFor(m => m.DOB)
                                @Html.HiddenFor(m => m.DOJ)
                                @Html.HiddenFor(m => m.ShiftNo)
                                @Html.HiddenFor(m => m.FirstName)
                                @Html.HiddenFor(m => m.CellPhone)
                                @Html.HiddenFor(m => m.HomePhone)
                                @Html.HiddenFor(m => m.EMail)
                                @Html.HiddenFor(m => m.EmpOfficeExt)
                                @Html.HiddenFor(m => m.EmpEmailId)
                                @Html.HiddenFor(m => m.EmpImgID)
    }
</div>

script

    function updateSuccess() {

        $.ajax({
            url: '@(Url.Action("UpdateProfile", "Profile"))',
            type: "POST",
            data: $('form').serialize(),
            success: function (data) {
                alert(data.status);
            },
            error: function (xhr, status, error) { alert(error); }
        });
    }

MVC Ajax begin form posts, with a "submit" inside the form will post the data to specified action method. Action method will return the MVC view and put inside the HTML id given in the attribute "UpdateTargetId". In the expample below, it will call Index
action of the same controller and gets the html string and replace the content inside my div with id ‘divHomeContent’.

@using
(Ajax.BeginForm(
"Index",
null,
new
AjaxOptions
{ UpdateTargetId =
"divhomeContent",InsertionMode
=InsertionMode.Replace

If you dont want to use MVC ajax, u can use jquery ajax. If you are using jquery ajax, u need to use
the form at all, you can pass all the inputs as data. In the button click you need to call a javascript method, inside the method u nee3d to use $.ajax() to make asynchronous request. If the action method returns mvc view, you can add the content to html container
using jquery. Or if the action method returns json, u need to work on json to html and add it to the html container. Some third party ui controls needs JSON. Only in this case we need to use jquery ajax, In other places MVC ajax is sufficient.

Leave a Reply