Search This Blog

Tuesday, 11 October 2022

Quick Tech Bits: MVC 5 working with Ajax Helper (Ajax.BeginForm)

 Integration of Ajax with MVC 5

1. Use Nuget Packages. Install them for your MVC project
    a. Microsoft.jQuery.Unobtrusive.Ajax
    b. Microsoft.jQuery.Unobtrusive.Validation

2. Verify if configurations are added in Web.config.
   ** Collapse all the folders for your project. The last file in your project will have capital "W" in     "Web.config"
   Check if the following is available inside <appSettings>
    <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />

3. Open _Layout.cshtml. (Find this in Views => Shared => _Layout.cshtml)
   Add the following in the same sequence as mentioned
    <script src="~/Scripts/jquery-<version>.min.js"></script>
        <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
 
   ** <version> : Look at the correct version of the file in the Scripts folder

4. Add an Action in the controller. The action should return a PartialView("yourView").

5. Create the Views for your action. Add @using(Ajax.BeginForm())
   Syntax for Ajax.BeginForm
    "YourActionNameOnClick", "ControllerName",
        new AjaxOptions
        {
            InsertionMode = InsertionMode.Replace | InsertionMode.InsertAfter | InsertionMode.InsertBefore,
            HttpMethod = "Get | Post | Put | Delete",
            UpdateTargetId = "resultDiv"
        }
6. This completes the configuration for ajax using MVC, Ajax helpers

No comments:

Post a Comment