Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Friday, January 15, 2016

Ajax.BeginForm Example - ASP.NET MVC

In this example I use an ajax form to load search results.

1) In my view I add the Ajax form.

The form invokes the "SearchResult" action

@using (Ajax.BeginForm("SearchResult", "Search", new AjaxOptions
{
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "searchResults"
}))
{
    <input type="text" name="q" />
    <input type="submit" value="Search" />  
}

<table id="searchResults">

</table>

2) The Action

public PartialViewResult SearchResult(string q)
        {
            var books = BookDB.GetBooks().Where(r => r.Name.Contains(q) || String.IsNullOrEmpty(q)).Take(10);
            return PartialView("_SearchResults", books);
        }

3)  The partial view to display search results

@using MvcBookReview.Infrastructure
@model IEnumerable<MvcBookReview.Models.BookReview>

<table id="searchResults">
    @foreach(var item in Model)
    {
    <tr>
        <td>
            <table>
                <tr>
                    <td><b>Book:</b> @item.Name</td>
                </tr>
                <tr>
                    <td><b>Rating:</b> @item.Rating</td>
                </tr>
            </table>
        </td>
        <td>
            <div class="bookitem">
                @Html.Image(item.ImageUrl, item.AlternateText)
            </div>
        </td>
    </tr>
    }
</table>

Note: Here I use the custom helper created in an earlier post


The Result: 
From left to right
    1) Search all
    2) Search text = "TinTin"
    3) Search text = "Asterix"


Wednesday, January 13, 2016

Ajax ActionLink - ASP.NET MVC

In this example I create an Ajax Action Link. Using the ActionLink load a partial view to the page.

1. In my view I create an ActionLink as

<div  id="latestReview">
    @Ajax.ActionLink("Get Latest Review", "LatestReview", new AjaxOptions
{
    UpdateTargetId = "latestReview",
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "GET",
    LoadingElementId = "progress"
})
</div >

also add another div for later use

<div id="progress">
    <img src="@Url.Content("~/Images/loading.gif")" />
</div >


In @Ajax.ActionLink()

  • The second parameter is the Action method which will be invoked on click
  • The third parameter specifies the ajax options


In the AjaxOption

  • The "UpdateTargetId" specifies the location in the DOM to display the result.
  • The "InsertionMode" provides the options such as Before, after or replace.
  • The "LoadingElementId" specifies the "progress" div to display until the view is partial view loaded

2. Next, in the controller create an Action method

In this example I omit the DB calls, instead create a dummy object of type BookReview. Note the return is a partial view


        public PartialViewResult LatestReview()
        {
            var modelTwo = new BookReview()
            {
                Name = "Samson",
                Rating = 7
            };
            Thread.Sleep(2000);
            return PartialView("_Review", modelTwo);
        }

a delay is created to show the "LoadingElementId" behaviour in the link

3. Create the partial view

@model MvcBookReview.Models.BookReview

<div class="review">
    <table class="rating">
        <tr class="ratinghead"><th>User</th><th>Rating</th></tr>
        <tr><td>@Model.Name</td><td>@Model.Rating</td></tr>
    </table>       
</div>

Note:
If you don't have the JQuery unobtrusive ajax library ("jquery.unobtrusive-ajax.min.js")in your solution, the ajax action link would not work properly. Add it to your solution through the Visual Studio Nuget Package Manager.

Result
The 3 stages: link, while processing action, result


When you have a look at the link through the browser's developer tool you will see something like this


Friday, February 20, 2015

AJAX call from Visual Web Part - SharePoint

1)
In the JavaScript function create the JSON object. Here the stringify method is used to construct the object which contains the parameters to be sent. The function in the JavaScript method of the aspx page is as below:


    function CallMyPage(itemValue, paramTwo, paramThree, paramFour) {

        var final = { myItem: itemValue, parameterTwo: paramTwo, parameterThree: paramThree, siteUrl: paramFour };

        $.ajax({
            type: "POST",
            url: paramFour + "/_layouts/15/MyFeatureFolder/WebMethods.aspx/MyWebMethod",
            data: JSON.stringify(final),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
           failure: function (response) {
             alert(response.d);
          }
       });
    }

2)
In the code behind within a SPGridView I have a HyperLink control. I set the JavaScript method call in the code behind as:

editLink.NavigateUrl = "javascript:CallMyPage('" + itemGuid.Text + "','" + MyParamTwo + "' ,'" + MyParamThree + "', '" + SPContext.Current.Web.Url + "');"; 


3)
In my approach instead of a web service I am using an application page (WebMethods.aspx) to get the job done. In the application page servicing the AJAX call, I create the web method

        [System.Web.Services.WebMethod]
        public static string MyWebMethod(string myItem, string parameterTwo, string parameterThree, string siteUrl)
        {
            string result = string.Empty;
            try 
            {
                //TODO - Process request and return result
            }
            catch (Exception)
            {
                //Exception Handling
            }
            return result;

4)
On success

    function OnSuccess(response) {

        if (response.d) {           
            /* Handle  result */            
        }
    }

Note: I have used the jquery-1.11.2.min.js file in my solution