我正在尝试在用户名表的每一行上创建一个按钮,该按钮会针对每个用户切换锁定/解锁功能。我想使用 AJAX,这样我就不必每次重新加载页面时都获取所有用户。在表中很容易有一个 AJAX 操作链接,但是在我锁定或解锁用户后,我一直不知道从我的控制器返回什么。作为一个小技巧,我返回一个字符串,它是一个新的 AJAX 操作链接的 html 标记。我理论上可以单击动态返回的按钮,然后继续切换锁定/解锁。令我惊讶的是,这确实有效,直到我点击了按钮。动态按钮确实返回正确的标记,但它在空白页上。为了使事情进一步复杂化,我正在使用自定义助手来输出我的操作链接。我已经详细说明了下面的所有代码,
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>