我試圖在每個用戶名錶的每一行上創建一個按鈕,以切換每個用戶的鎖定/解鎖功能。我想使用AJAX,所以我不必在每次重新加載頁面時都獲取所有用戶。它很容易在表中有一個AJAX動作鏈接,但是當我鎖定或解鎖用戶後,我被困在從控制器返回的內容中。作爲一種破解,我返回一個字符串,這是一個新的AJAX操作鏈接的html標記。我理論上我可以點擊動態返回的按鈕,並繼續切換鎖定/解鎖。令我驚訝的是,這實際上奏效了,直到我點擊按鈕。動態按鈕確實會返回正確的標記,但它在空白頁上。使問題更加複雜化,我使用自定義助手來輸出我的操作鏈接。我已經詳細介紹了下面的所有代碼,如果有人能夠看到可能出現的問題或更好的方式來處理這種情況,我會很感激。動態地從控制器動作返回一個AJAX動作鏈接
HTML助手:
public static string ImageActionLink(this AjaxHelper helper, string imageUrl, string altText, string actionName, object routeValues, AjaxOptions ajaxOptions)
{
var builder = new TagBuilder("img");
builder.MergeAttribute("src", imageUrl);
builder.MergeAttribute("alt", altText);
var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions);
return link.ToHtmlString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing));
}
控制器:
public string Lock(Guid id)
{
IUserMethods userMethods = new UserMethods();
ISMPUser user = userMethods.GetUser(id, CompanyId);
string ajaxButtonHTML;
//For some reason breaking the button HTML into substrings and appending them together for readability causes the anchor tag to render incorrectly.
if (user.IsEnabled)
{
userMethods.AdministratorEnableAccount(CompanyId, CurrentUser.Id, user.Username, false);
ajaxButtonHTML = "<a class=\"row_selected\" href=\"/MMWeb/Admin/Lock/" + id.ToString() + "\" onclick=\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, confirm: 'Lock User?', httpMethod: 'Post', updateTargetId: 'Enable-'" + user.Id + "' });\"><img src=\"/MMWeb/Content/Images/lock.png\" alt=\"Lock\"></a>";
}
else
{
userMethods.AdministratorEnableAccount(CompanyId, CurrentUser.Id, user.Username, true);
ajaxButtonHTML = "<a class=\"row_selected\" href=\"/MMWeb/Admin/Lock/" + id.ToString() + "\" onclick=\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, confirm: 'Lock User?', httpMethod: 'Post', updateTargetId: 'Enable-'" + user.Id + "' });\"><img src=\"/MMWeb/Content/Images/unlock.png\" alt=\"Unlock\"></a>";
}
return ajaxButtonHTML;
}
查看:
<td id="<%= Html.Encode("Enable-" + user.Id) %>" class="icon-column">
<% if(user.IsEnabled)
{ %>
<%--<img class="LockImg" alt="User Unlocked" src="<%= Url.Content("~/Content/Images/unlock.png") %>" />--%>
<%= Ajax.ImageActionLink(Url.Content("~/Content/Images/unlock.png"), "Lock", "Lock", new { id = user.Id.ToString() }, new AjaxOptions { Confirm = "Lock User?", HttpMethod = "Post", UpdateTargetId = "Enable-" + user.Id })%>
<% }
else
{%>
<%= Ajax.ImageActionLink(Url.Content("~/Content/Images/lock.png"), "Lock", "Lock", new { id = user.Id.ToString() }, new AjaxOptions { Confirm = "Unlock User?", HttpMethod = "Post", UpdateTargetId = "Enable-" + user.Id })%>
<% }%>
</td>