ASP.NET MVC – HTMLHelper + AJAX – Menu Button + Target ID with Partial View
HTMLHelper |
using System; using System.Web.Mvc; public static class WebAJAX { public static MvcHtmlString AJAXLink(string id, string targetid, string url, string text, string @class=null) { return new MvcHtmlString(String.Format("<span class='ajaxlink {2}' data-url='{3}' for='{0}'>{1}</span>", targetid, text, @class, url)); } } |
Controller |
using System.Web; using System.Web.Mvc; using System.Threading.Tasks; public ActionResult Index() { return View(); } [HttpGet] public async Task<ActionResult> MenuItemA(int? id) { … … return PartialView(); } [HttpGet] public async Task<ActionResult> MenuItemB(int? id) { … … return PartialView(); } [HttpGet] public async Task<ActionResult> MenuItemC(int? id) { … … return PartialView(); } |
View |
@using WebApp.Helper; <style> .menuitem { display:block; line-height:28px; padding-left:8px; cursor:pointer; } .menuitem:hover { background-color:#DDDDDD; } </style> < table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td width="15%" valign="top"> < div> @(WebAJAX.AJAXLink("ItemA", "content", "./MenuItemA?id=1", "Item A", "menuitem")) @(WebAJAX.AJAXLink("ItemB", "content", "./MenuItemB?id=2", "Item B", "menuitem")) @(WebAJAX.AJAXLink("ItemC", "content", "./MenuItemC?id=3", "Item C", "menuitem")) </div> </td> <td width="85%" valign="top"> < div id="content" style="border:1px solid #CCCCCC; width:100%; height:600px;"> </div> </td> </tr> </table> |
JavaScript |
$(document).ready(function () { AJAXLink(); }); function AJAXLink() { $(".ajaxlink").click(function () { id = "#" + $(this).attr("for"); url = $(this).attr("data-url"); $(id).load(url); }); } |