Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax helper in ASP.net MVC

I know that this question may not be fit for stack overflow. I've been searching for an example on how to use the ajax helper but most toturials have only gone through the helper and they have not provided any practical example. I already know how to make use of ajax the javascript way but just want to know how I can use the ajax helper that microsoft has provided.

like image 949
JAX Avatar asked Mar 19 '23 06:03

JAX


1 Answers

To describe how this GitHUb branch works:

First, let's define an action we're going to request. To keep things simple, let's just make a very basic POST action:

//
// POST: /Home/Ajax
[HttpPost]
public PartialViewResult Ajax()
{
    // use partial view so we're not bringing the entire page's theme
    // back in the response. We're simply returning the content within
    // ~/Views/Home/Ajax.cshtml
    return PartialView();
}

Next, setup a destination for your content and give it an id (here I've named it "update-me"):

<div class="well" id="update-me">
  Click the button to see some AJAX content.
</div>

Moving on from there we setup the form. The below demonstrates the standard AJAX functionality, but you could bind your own functions to some of the events specified by AjaxOptions.

@using (Ajax.BeginForm("Ajax", new AjaxOptions {
    HttpMethod = "POST", // HttpPost
    InsertionMode = InsertionMode.Replace, // empty the target first
    UpdateTargetId = "update-me" // place content within #update-me
}))
{
    <button type="submit" class="btn btn-default">
        <i class="glyphicon glyphicon-refresh"></i>
        Click Me!
    </button>
}

And finally, we need to specify our script libraries responsible for most of the ["automatic"] wiring up of the form functionality:

<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

That's it. As you begin playing with it you'll find it's pretty simple to extend it. For example, if you wanted to show a "working" icon you could specify custom functions in the OnBegin and OnComplete properties.

like image 107
Brad Christie Avatar answered Mar 29 '23 11:03

Brad Christie