How to use AJAX In ASP.NET MVC
By FoxLearn 2/18/2024 1:39:54 AM 275
It's a fundamental for modern web applications.
You can create a new ASP.NET MVC project, then open _Layout file in the View\Shared folder and modify your html code as shown below.
<ul class="nav navbar-nav"> <li>@Ajax.ActionLink("Home", "Index", "Home", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "ContentPanel" })</li> <li>@Ajax.ActionLink("About", "About", "Home", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "ContentPanel" })</li> <li>@Ajax.ActionLink("Contact", "Contact", "Home", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "ContentPanel" })</li> </ul>
Remember add id = "ContentPanel" to div tag, it will be pasted content of your Partial View when calling an ajax action link. As you can see UpdateTargetId = "ContentPanel" and InsertionMode = InsertionMode.Replace in Ajax.ActionLink
<div id = "ContentPanel" class="container body-content"> @RenderBody() <hr /> <footer> <p>© @DateTime.Now.Year - My ASP.NET Application</p> </footer> </div>
Open HomeController, then modify the return code to PartialView instead of View
public class HomeController : Controller { public ActionResult Index() { return PartialView(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return PartialView(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return PartialView(); } }
Open About view, then modify as below
@{ ViewBag.Title = "About"; Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml"; }
If ajax calls you should set the layout to null and vice versa. You can do the same as for Contact and Index actions.
Remember install jquery.unobtrusive-ajax from Nuget Package Manager, then set UnobtrusiveJavaScriptEnabled is true in the web.config. Let's play demo you can see how to it work.
<appSettings> <add key="webpagesersion" value="2.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="PreserveLoginUrl" value="true" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings>
- How to use CORS in ASP.NET Core
- How to Send Emails in ASP.NET Core
- How to Run Background Tasks in ASP.NET Core with Hosted Services
- Implementing Scheduled Background Tasks in ASP.NET Core with IHostedService
- Creating an Web API in ASP.NET Core
- 8 Essential Tips to Protect Your ASP.NET Core Application from Cyber Threats
- 10 Common Mistakes ASP.NET Developers Should Avoid
- How to Upload Files Using C# ASP.NET FileUpload Control