This is a migrated thread and some comments may be shown as answers.

View doesn't update after window closes 2nd time

2 Answers 244 Views
Data Source
This is a migrated thread and some comments may be shown as answers.
Jon
Top achievements
Rank 1
Jon asked on 07 Mar 2012, 10:13 PM
Greetings,

I have a popup window that allows the user to edit the email address.
When the "Save" button is clicked, the change is saved and the form updates correctly.
When the form is closed, the Email column on the grid of the parent page also updates correctly, and changes to the new value. The update occurs via an ajax call.

The problem is that every time I open a window after the first time, the view doesn't update and the grid does not show the new changes. If I hit the "F5" key the page and grid update correctly, like it did the first time I closed the window.

The code is below and I would greatly appreciate any ideas as to why the parent page only updates correctly after the window closes the first time. I am new to MVC, Jquery and Kendo, so a basic example with instructions would really help me the  most.

Thanks

//_Layout.cshtml
 
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Styles/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("http://code.jquery.com/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("http://code.jquery.com/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/kendo.all.min.js")" type="text/javascript"></script>
    <link href="@Url.Content("~/Styles/kendo.common.min.css")" rel="stylesheet" />
    <link href="@Url.Content("~/Styles/kendo.default.min.css")" rel="stylesheet" type="text/css" />
 
</head>
<body>
    <div class="page">
        <header>
            <nav>
                <ul id="menu">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Customer Service", "CustomerService", "Home")</li>
                    <li>@Html.ActionLink("Producers & Brokers Agencies", "ProducersBrokerAgencies", "Home")</li>
                    <li>@Html.ActionLink("Partner Agencies", "PartnerAgencies", "Home")</li>
                    <li>@Html.ActionLink("Internal Users", "InternalUsers", "Home")</li>
                    <li>@Html.ActionLink("Members", "Members", "Home")</li>
                    <li>@Html.ActionLink("Billing", "Billing", "Home")</li>
                    <li>@Html.ActionLink("Reports", "Reports", "Home")</li>
                </ul>
            </nav>
        </header>
        <section id="main">
            @RenderBody()
        </section>
        <footer>
        </footer>
    </div>
</body>
</html>

//CustomerService.cshtml
 
@{
    ViewBag.Title = "Customer Service View";
}
 
<h2>@ViewBag.Message</h2>
<p>
    Customer Service Page View
 
</p>
 <div id="example" class="k-content">
    <div id="window" style="width:100%;"> </div>
    <div id="grid"></div>
 
    <script type="text/javascript">
        var dateRegExp = /^\/Date\((.*?)\)\/$/;
 
        function toDate(value)
        {
            var date = dateRegExp.exec(value);
            return new Date(parseInt(date[1]));
        }
 
        $(document).ready(function () {
            $("#grid").kendoGrid({
                dataSource: {
                    type: "json",
                    transport: {
                        read: "JsonGetUsers"
                    },
                    schema: {
                        model: {
                            fields: {
                                Username: { type: "string" },
                                UserId: { type: "string" },
                                Email: { type: "string" },
                                LastLoginDate: { type: "date" },
                                DaysSinceActive: { type: "int" },
                                Name: { type: "string" },
                                DetailsLink: { type: "string" }
                            }
                        }
                    },
                    pageSize: 100
                },
 
                height: 410,
                filterable: true,
                sortable: true,
                pageable: true,
                columns: [
                    "Username",
                    "Email",
                    { field: "LastLoginDate", template: '#= kendo.toString(toDate(LastLoginDate), "MM/dd/yyyy") #' },
                    "DaysSinceActive",
                    "Name",
                    {
                        title: "", width: "180px", template: '#= ShwEdit(DetailsLink)#',
                        filterable: false
                    }
                ]
            });
 
        });
 
            function ShwEdit(d) {
                var dlink = '<input type="button" value="Details" class="k-button" id="btnstatus" style="height:27px;"  onclick="ShowPop(' + "'" + d + "'" + ')"/>';
                return dlink;
        }
 
        function ShowPop(d)
        {
            var win = $("#window");
 
         if (!win.data("kendoWindow"))
         {
          // window not yet initialized
            win.kendoWindow({
                width: 920,
                height: 620,
                actions: ["Refresh", "Maximize", "Minimize", "Close"],
                content: d,
                title: "User Details",
                draggable: true,
                modal: true,
                resizable: false,
                close: onClose,
                refresh: function () { this.center(); }
            }).data("kendoWindow").center().open();
        }
        else {
            // reopening window
            win.data("kendoWindow")
                .refresh(d) // request the URL via AJAX
                .title("User Details")
                .center().open();  // open the window;
        }
    }
 
    function onClose(e) {
        $.ajax(
        {
            type: "GET",
            url: "/Home/JsonGetUsers",
            success: function (result) {
                var grid = $("#grid").data("kendoGrid");
                grid.dataSource.data(result);
                grid.dataSource.sync();
                grid.refresh();
            },
            error: function (result) {
                alert('error');
            }
        });
    }
 
    </script>
</div>

//UserDetailView on popup window
 
@model WebAdmin3.WebApp.Models.UserDetail
 
@{
    ViewBag.Title = "User Details";
}
 
<h2>User Details for @Model.Username</h2>
<fieldset style="width: 98%; padding: 0.4em;">
    <div id="divButton" style="margin-left:96%; margin-top:1%; width: 4%; ">
            <span id="editUser" class="k-group" style="text-align: center; white-space: nowrap; border-width: 1px; border-style: solid; padding: .2em; cursor: pointer;">Edit</span>
        </div>   
    <table style="width:100%; border: 0;">
<tr>
    <td style="border: 0; width: 14%;">User Name:</td><td style="border: 0; width: 24%;">@Model.Username</td>
    <td style="border: 0; width: 14%;">Email:</td><td style="border: 0; width: 44%;"><label id="lblEmail">@Model.Email</label> <input type="text" id="txtemail" name="txtemail" style="display:none; font-size: 1em;"/></td>
</tr>
<tr>
    <td style="border: 0; width: 14%;">Creation Date:</td><td style="border: 0; width: 14%;">@Model.CreationDate</td>
    <td style="border: 0; width: 14%;">Last Activity Date:</td><td style="border: 0; width: 44%;">@Model.LastActivityDate</td>
</tr>
<tr>
    <td style="border: 0; width: 14%;">Last Login Date:</td><td style="border: 0; width: 14%;">@Model.LastLoginDate</td>
    <td style="border: 0; width: 14%;">Is Locked Out:</td><td style="border: 0; width: 44%;">@Model.IsLockedOut</td>
</tr>
<tr>
    <td style="border: 0;">
        <span id="manageSecurity" class="k-group" style="text-align: center; white-space: nowrap; border-width: 1px; border-style: solid; padding: .2em; cursor: pointer;">Manage Security</span>
    </td>
</tr>
<tr>
<td colspan="4" style="border: 0;">
    <div id="divSaveButton" style="margin-bottom:1%; margin-left:90%; width: 12%; ">
        <span id="saveUser" class="k-group" style="display:none;  text-align: left; white-space: nowrap; border-width: 1px; border-style: solid; padding: .2em; cursor: pointer;">Save</span>
        <span id="cancelUser" class="k-group" style="display:none;  text-align: right; white-space: nowrap; border-width: 1px; border-style: solid; padding: .2em; cursor: pointer;">Cancel</span>
    </div>
</td>
</tr>
</table>
    <div id="divManageSecurity" style="float: left; width: 99%; background-color: #FFFFEC;
    border: thin groove #C0C0C0; padding: 4px;">
     
    <div style="width: 62%; float: left; font-size: 0.8em; line-height: 0.4em;" >
        <fieldset style="margin: 4px; width: 100%; padding: 0.4em;">
            <legend>Security Options</legend>
            <p>
                You may use the auto generated password (pre-populated in the new password box) <strong>or</strong><br />
                change to a <em>customer requested password</em>. The generated password is <span
                class="style2">intentionally invalid</span>.
            </p>
            <ul style="padding-left: 20px">
                <li><em>customer requested password</em> must be 8 - 20 characters in length.</li>
                <li><em>customer requested password</em> must contain at least 1 upper case and 1 lower
                case letter</li>
                <li><em>customer requested password</em> must have both letters AND numbers) </li>
            </ul>
            <span style="color: Red">* </span>
            <label id="lblpasswordLabel">New Password:</label>
            <input type="text" id="txtPassword" name="txtPassword" />
            <span id="checkPassword" class="k-group" style="text-align: left; white-space: nowrap; border-width: 1px; border-style: solid; padding: .2em; cursor: pointer;">Check Password</span>
               <br /><br />
 
            <p>
                <span id="disableUser" class="btnRed" >Disable User</span>
                  
                <span id="resetAnswers" class="btnOrange">Reset Security Answers</span>
                  
                <span id="passwordReset" class="btnGreen">Password Reset</span>
                  
                <span id="unlockUser" class="btnGreen">Unlock User</span>
        </p>
        </fieldset>
    </div>       
 
     <div style="width: 36%; float: right; font-size: 0.8em; line-height: 0.4em;">
        <fieldset style="width: 90%; padding: 4%; margin-top:2.44%;">
            <div id="divRoleLabelTitle" style="width: 26%; float:left;">
                <label id="lblCurrentBillingRoleTitle">Billing Role:</label>
            </div>
            <div id="divRoleLabel" style="width:60%; float:left;">
                <b><label id="lblCurrentBillingRole">No Billing</label> </b>
            </div>
            <div id="divEditLinkBilling" style="width:8%; float:right;">
                <span id="lbtBillingEditRoleRadios" class="k-group" style="text-align: center; white-space: nowrap; border-width: 1px; border-style: solid; padding: .2em; cursor: pointer;">Edit</span>
            </div>
            <div id="divBillingNoneRadio" style="width: 98%; float:left; margin-left: 1%; margin-top:2%;">
                <input type="radio" name="rdoBillingNone" value="none" CHECKED />
                <label id="lblNoBillingRole">No Billing Access</label>
            </div>
            <div id="divBillingRadio" style="width: 98%; float:left; margin-left: 1%;">
                <input type="radio" name="rdoBilling" value="billing" />
                <label id="lblBillingRole">Billing - View Only</label>
            </div>
            <div id="divBillingFullRadio" style="width: 98%; float:left; margin-left: 1%;">
                <input type="radio" name="rdoBillingFull" value="billing" />
                <label id="lblFullBillingRole">Billing - Full Access</label>
            </div>
            <div id="divBillingRoleButtons" style="float:right;">
                <span id="btnSaveBillingRole" class="btnGreen">Save</span>
                  
                <span id="btnCancelBillingRole" class="btnGreen">Cancel</span>
            </div>
        </fieldset>
 
        <fieldset style="width: 96%; padding: 1%;" id="fldRoles;">
            <div id="divEditLinkRoles" style="width:10%; float:right; margin-top: 4%;">
                <span id="lbtEditRolesRadios" class="k-group" style="text-align: center; white-space: nowrap; border-width: 1px; border-style: solid; padding: .2em; cursor: pointer;">Edit</span>
            </div>
 
            <fieldset style="width: 97%; padding: 1%; margin-top:10%;" id="fldEnrollment">
                <div runat="server" id="divEnrollmentNoneRadio" style="width: 99%; float:left; margin-left: 1%;">
                    <input type="radio" name="rdoEnrollmentNone" value="none" CHECKED />
                    <label id="lblNoEnrollmentRole">No Enrollment Access</label>
                </div>
                <div runat="server" id="divEnrollmentRadio" style="width: 99%; float:left; margin-left: 1%;">
                    <input type="radio" name="rdoEnrollment" value="none" />
                    <label id="lblEnrollmentRole">Enrollment - View Only</label>
                </div>
                <div runat="server" id="divEnrollmentFullRadio" style="width: 99%; float:left; margin-left: 1%;">
                    <input type="radio" name="rdoEnrollmentFull" value="none" />
                    <label id="lblEnrollmentFullRole">Enrollment - Full Access</label>
                </div>
            </fieldset>
 
            <fieldset style="width: 97%; padding: 1%;" id="fldClaims">
                <div runat="server" id="divClaimsNoneRadio" style="width: 99%; float:left; margin-left: 1%;">
                    <input type="radio" name="rdoClaimsNone" value="none" SELECTED />
                    <label id="lblClaimsNone">No Claims Access</label>
                </div>
                <div runat="server" id="divClaimsRadio" style="width: 99%; float:left; margin-left: 1%;">
                    <input type="radio" name="rdoClaims" value="none"/>
                    <label id="lblClaims">Claims</label>
                </div>
          </fieldset>
 
        <div id="divResetRoleButton" runat="server" style="width:42%; float:left; margin-bottom:2%;">
            <span id="btnResetSecurity" class="btnBlue">Reset to Employer</span>
        </div>
 
        <div id="divRoleButtons" runat="server" style="float:right; margin-bottom:2%;">
            <span id="btnSaveSecurity" class="btnGreen">Save</span>
               
            <span id="btnCancelRole" class="k-group" style="text-align: center; white-space: nowrap; border-width: 1px; border-style: solid; padding: .2em; cursor: pointer;">Cancel</span>
        </div>
        </fieldset>
     </div>
</div>
<label id="lblUserID" style="color:#cacaca" >@Model.UserId</label>
  
</fieldset>
  <script type="text/javascript">
      $(document).ready(function () {
          //hide buttons
          $('#divManageSecurity').hide();
          $('#btnSaveBillingRole').hide();
          $('#btnCancelBillingRole').hide();
          $('#btnResetSecurity').hide();
          $('#btnSaveSecurity').hide();
          $('#btnCancelRole').hide();
 
          //buttons in enrollment/claims section
          $('#btnResetSecurity').click(function () {
              $('#btnResetSecurity').hide();
              $('#btnSaveSecurity').hide();
              $('#btnCancelRole').hide();
              $('#lbtEditRolesRadios').show();
          });
 
          $('#btnSaveSecurity').click(function () {
              $('#btnResetSecurity').click();
          });
 
          $('#btnCancelRole').click(function () {
              $('#btnResetSecurity').click();
          });
 
          $('#lbtEditRolesRadios').click(function () {
              $('#btnResetSecurity').show();
              $('#btnSaveSecurity').show();
              $('#btnCancelRole').show();
              $('#lbtEditRolesRadios').hide();
          });
 
          //buttons in billing section
          $('#lbtBillingEditRoleRadios').click(function () {
              $('#btnSaveBillingRole').show();
              $('#btnCancelBillingRole').show();
              $('#lbtBillingEditRoleRadios').hide();
          });
 
          $('#btnSaveBillingRole').click(function () {
              $('#btnSaveBillingRole').hide();
              $('#btnCancelBillingRole').hide();
              $('#lbtBillingEditRoleRadios').show();
          });
 
          $('#btnCancelBillingRole').click(function () {
              $('#btnSaveBillingRole').click();
          });
 
          //buttons on main form
          $('#manageSecurity').click(function () {
              $('#divManageSecurity').slideToggle();
          });
 
          $('#divButton > #editUser').click(function () {
              $('#txtemail').show();
              $('#txtemail').val("@Model.Email");
              $('#editUser').hide();
              $("#lblEmail").hide();
              $('#saveUser').show();
              $('#cancelUser').show();
          });
 
          $('#divSaveButton > #saveUser').click(function () {
              $.post('@Url.Action("SaveEmail")',
                    { newEmail: $('#txtemail').val(), userId: $('#lblUserID').text() },
                    function (result) {
                        // the value was successfully posted to the server
                        var windowObject = $("#window").data("kendoWindow");
                        windowObject.refresh();
 
                    });
 
          });
 
          $('#divSaveButton > #cancelUser').click(function () {
              $('#txtemail').hide();
              $('#txtemail').val("");
              $('#editUser').show();
              $("#lblEmail").show();
              $('#saveUser').hide();
              $('#cancelUser').hide();
          });
      });
  </script>

/Home Controller and all actions
 
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;
using WebAdmin3.WebApp.Models;
using System.Web.Security;
 
namespace WebAdmin3.WebApp.Controllers
{
    public class HomeController : Controller
    {
 
        public static DataSet ExecuteDataSet(SqlCommand sqlCmd, string connectionString)
        {
            if (connectionString == null)
                throw (new ArgumentNullException("connectionString"));
 
            if (connectionString.Length == 0)
                throw (new ArgumentOutOfRangeException("connectionString"));
 
            if (sqlCmd == null)
                throw (new ArgumentNullException("sqlCmd"));
 
            using (var cn = new SqlConnection(connectionString))
            {
                sqlCmd.Connection = cn;
                cn.Open();
                var da = new SqlDataAdapter(sqlCmd);
                var ds = new DataSet();
                da.Fill(ds);
                return (ds);
            }
        }
 
        public static void AddParameterToSqlCmd(SqlCommand sqlCmd, string parameterId,
                                        SqlDbType sqlType, int parameterSize,
                                        ParameterDirection parameterDirection, object parameterValue)
        {
            if (sqlCmd == null)
                throw (new ArgumentNullException("sqlCmd"));
            if (parameterId == null)
                throw (new ArgumentNullException("parameterId"));
            if (parameterId.Length == 0)
                throw (new ArgumentOutOfRangeException("parameterId"));
 
            if (parameterValue == null)
                parameterValue = DBNull.Value;
 
            var newSqlParam = new SqlParameter
            {
                ParameterName = parameterId,
                SqlDbType = sqlType,
                Direction = parameterDirection
            };
 
            if (parameterSize > 0)
                newSqlParam.Size = parameterSize;
 
            if (parameterValue != null)
                newSqlParam.Value = parameterValue;
 
            sqlCmd.Parameters.Add(newSqlParam);
        }
 
        private static DataSet GetCustomers()
        {
            using (var cmd = new SqlCommand("usp_GetEPRecordsWithMembership"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
 
                AddParameterToSqlCmd(cmd, "recType", SqlDbType.NVarChar, 50, ParameterDirection.Input, @"extranet\employer");
                AddParameterToSqlCmd(cmd, "db", SqlDbType.NVarChar, 50, ParameterDirection.Input, @"LSVSitecore_Core");
                AddParameterToSqlCmd(cmd, "pilotuser", SqlDbType.NVarChar, 50, ParameterDirection.Input, @"extranet\pilot employer");
                AddParameterToSqlCmd(cmd, "manualSecurityUser", SqlDbType.NVarChar, 50, ParameterDirection.Input, @"extranet\employer manual security");
                return ExecuteDataSet(cmd, @"user id=WebAdmin;password=Usable1234;Data Source=USLWEBDEV2\WEBSQL2K5DEV;Database=ExternalSystems");
            }
        }
 
        private static UserDetail GetUserDetailById(string userId)
        {
            var userDetailData = new UserDetail();
            if (string.IsNullOrEmpty(userId)) return null;
 
            var mu = Membership.GetUser(new Guid(userId));
            if (mu == null) return null;
 
            userDetailData.Username = mu.UserName;
            userDetailData.Email = mu.Email;
            userDetailData.UserId = userId;
            userDetailData.CreationDate = mu.CreationDate;
            userDetailData.LastActivityDate = mu.LastActivityDate;
            userDetailData.LastLoginDate = mu.LastLoginDate;
            userDetailData.IsLockedOut = mu.IsLockedOut;
            return userDetailData;
        }
         
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult JsonGetUsers()
        {
            var data = GetCustomers(); //returns a dataset from a SQL table
            var customerList = new List<CustomerService>();
            foreach (DataRow dr in data.Tables[0].Rows)
            {
                var cl = new CustomerService();
                int days;
                DateTime lastlogin;
                int.TryParse(dr["DaysSinceActive"].ToString(), out days);
                DateTime.TryParse(dr["LastLoginDate"].ToString(), out lastlogin);
                cl.DaysSinceActive = days;
                cl.Email = dr["LoweredEmail"].ToString();
                cl.LastLoginDate = lastlogin;
                cl.Name = dr["FullName"].ToString();
                cl.Username = dr["Username"].ToString();
                cl.UserId = dr["userid"].ToString();
                cl.DetailsLink = "UserDetailView/" + cl.UserId;
                customerList.Add(cl);
            }
 
            return Json(customerList, JsonRequestBehavior.AllowGet);
        }
 
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to WebAdmin";
 
            return View();
        }
 
        public ActionResult About()
        {
            return View();
        }
 
        public ActionResult CustomerService()
        {
            ViewBag.Message = "Customer Service Home";
            return View();
        }
 
        public ActionResult ProducersBrokerAgencies()
        {
            ViewBag.Message = "Producers & Broker Agencies Home";
            return View();
        }
 
        public ActionResult PartnerAgencies()
        {
            ViewBag.Message = "Partner Agencies Home";
            return View();
        }
 
        public ActionResult InternalUsers()
        {
            ViewBag.Message = "Internal Users Home";
            return View();
        }
 
        public ActionResult Members()
        {
            ViewBag.Message = "Members Home";
            return View();
        }
 
        public ActionResult Billing()
        {
            ViewBag.Message = "Billing Home";
            return View();
        }
 
        public ActionResult Reports()
        {
            ViewBag.Message = "Reports Home";
            return View();
        }
 
          
        public ActionResult UserDetailView(string id)
        {
            var ddata = GetUserDetailById(id);
            return PartialView(ddata);
        }
 
        [HttpPost]
        public ActionResult SaveEmail(string newEmail, string userId)
        {
            var mu = Membership.GetUser(new Guid(userId));
            mu.Email = newEmail;
            Membership.UpdateUser(mu);
            return RedirectToAction(@"UserDetailView/" + userId, "Home");
        }
 
 
    }
}

//Customer Service Model
 
using System;
 
namespace WebAdmin3.WebApp.Models
{
    public class CustomerService
    {
        public string UserId { get; set; }
        public string Username { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public DateTime LastLoginDate { get; set; }
        public int DaysSinceActive { get; set; }
        public string DetailsLink { get; set; }
    }
}

//UserDetail Model used on detail popup
using System;
 
namespace WebAdmin3.WebApp.Models
{
    public class UserDetail
    {
        public string UserId { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public DateTime CreationDate { get; set; }
        public DateTime LastActivityDate { get; set; }
        public DateTime LastLoginDate { get; set; }
        public bool IsLockedOut { get; set; }
    }
}

//connection string in web.config in configuration section
 //add your own table and userid/password credentials below
    <connectionStrings>
        <add name="CoreConn" connectionString="user id=;password=;Data Source=serverName\databaseName;Database=database" />
  </connectionStrings>

//membership provider variables for Membership functoinality in web.config in system.web section
  <membership defaultProvider="sql" userIsOnlineTimeWindow="15">
          <providers>
              <clear />
              <add name="sql" type="System.Web.Security.SqlMembershipProvider"
          connectionStringName="CoreConn"
          applicationName="sitecore"
          minRequiredPasswordLength="1"
          minRequiredNonalphanumericCharacters="0"
          requiresQuestionAndAnswer="false"
          requiresUniqueEmail="false"
          maxInvalidPasswordAttempts="2" />
          </providers>
      </membership>

2 Answers, 1 is accepted

Sort by
0
Jon
Top achievements
Rank 1
answered on 07 Mar 2012, 10:19 PM
FYI,

This bug only happens in IE 8. It works fine in Firefox.

Thanks
0
Jon
Top achievements
Rank 1
answered on 07 Mar 2012, 10:38 PM
I fixed it.

In IE, I had to go to options and turn off caching.

Tags
Data Source
Asked by
Jon
Top achievements
Rank 1
Answers by
Jon
Top achievements
Rank 1
Share this question
or