Wednesday, November 21, 2012

Asp.Net MVC 4–Creating an AJAX page and using JQueryUI dialog

This is a very quick tutorial on how to create a page that displays data using AJAX. In addition, I will also show how to use the JQueryUI dialog element.

First a quick description of the page we are going to build:

image

There are 5 links on the page. When you click on one of the links 2 parts of the page are updated via jquery. (The div at the bottom and the dialog to the right).

Step 1: Create a MVC 4 Internet application.
Create a new MVC 4 internet application project, which we will use for this tutorial.

Step 2: Check to make sure “UnobtrusiveJavaScriptEnabled” is set to true in your web.config file.

Step 3: Add the references to the unobtrusive scripts in _layout.cshtml:
This is done by adding the line: @Scripts.Render("~/bundles/jqueryval") right after the line: @Scripts.Render("~/bundles/jquery")
image

Note: FYI: The reference to “~/bundles/jqueryval” is based on the bundle names defined in “BundleConfig.cs”.

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));

Step 3: Add a new action to the HomeController, that will return a partial view:

public ActionResult IndexData(int id)
        {
            ViewBag.Id = id;
            ViewBag.Title = "The ID is: " + id;
            return PartialView();
        }

Step 4: Create a view for the IndexData action:

Right click in the action and select “Add View” and select the defaults.

Add the following code to the new IndexData.cshtml page:

@{
   
}
@Html.Hidden("Id",(int)ViewBag.Id)
@Html.TextBox("Title",(string)ViewBag.Title)

Step 4:Update Index.cshtml to show the links and allow calls to occur using AJAX:

Add a reference to the CSS files used by JqueryUi by adding the following code:

@Styles.Render("~/Content/themes/base/css")

Add an Ajax.ActionLink:

@Ajax.ActionLink("ajax load for id: 101", "IndexData", new {id = 101}, new AjaxOptions {HttpMethod = "Get", InsertionMode = InsertionMode.Replace, OnSuccess = "SuccessFunction", UpdateTargetId = "myDiv"})

The above line, adds a link with the text “ajax load for id: 101”. It will call the “IndexData” action on the HomeController and it will pass it the value of 101. Finally, check out the AjaxOptions values:
- The AJAX call will be performed as a GET operation
- The call will result in replacing the DOM with the data that is returned
- If the call succeeds, the “SuccessFunction” will be called.
- Finally the data that is returned by the ajax call will update a DOM element named “myDiv”

We will add a few more such links:

@Ajax.ActionLink("ajax load for id: 202", "IndexData", new {id = 202}, new AjaxOptions {HttpMethod = "Get", InsertionMode = InsertionMode.Replace, OnSuccess = "SuccessFunction", UpdateTargetId = "myDiv"})
<br/>
@Ajax.ActionLink("ajax load for id: 303", "IndexData", new {id = 303}, new AjaxOptions {HttpMethod = "Get", InsertionMode = InsertionMode.Replace, OnSuccess = "SuccessFunction", UpdateTargetId = "myDiv"})
<br/>

The next step is to add a couple of divs that will be used to display the data.

<div id="myDiv"></div>
<div id="myDiv2" style="border-width: medium; border-color: black"></div>

The first div will be used for the dialog and the 2nd div for updating a DOM element directly on the page.

Finally:

Add the following code to the end of the page:

@section scripts
{
    @Scripts.Render("~/bundles/jqueryui")
    <script>
        $(function() {
            $("#myDiv").dialog({ autoOpen: false });
        });
        function SuccessFunction(data) {
            $("#myDiv").dialog("open");

            $("#myDiv2").html(data);
        }
    </script>
}

Lets break down the code:

1. @Scripts.Render("~/bundles/jqueryui"): This line adds the reference to the JqueryUI scripts

2. $(function() : The ready-function, sets up myDiv to be a dialog. In addition, it sets it up to not open by default.

3. function SuccessFunction: This is the function that is called when the Ajax calls return. It opens the dialog and also updates the 2nd div to show the same data in 2 different ways.

Final code for the index.cshtml

@{
    ViewBag.Title = "Home Page";
}
@Styles.Render("~/Content/themes/base/css")
@Ajax.ActionLink("ajax load for id: 101", "IndexData", new {id = 101}, new AjaxOptions {HttpMethod = "Get", InsertionMode = InsertionMode.Replace, OnSuccess = "SuccessFunction", UpdateTargetId = "myDiv"})
<br/>
@Ajax.ActionLink("ajax load for id: 202", "IndexData", new {id = 202}, new AjaxOptions {HttpMethod = "Get", InsertionMode = InsertionMode.Replace, OnSuccess = "SuccessFunction", UpdateTargetId = "myDiv"})
<br/>
@Ajax.ActionLink("ajax load for id: 303", "IndexData", new {id = 303}, new AjaxOptions {HttpMethod = "Get", InsertionMode = InsertionMode.Replace, OnSuccess = "SuccessFunction", UpdateTargetId = "myDiv"})
<br/>
<div id="myDiv"></div>
<div id="myDiv2" style="border-width: medium; border-color: black"></div>
@section scripts
{
    @Scripts.Render("~/bundles/jqueryui")
    <script>
        $(function() {
            $("#myDiv").dialog({ autoOpen: false });
        });
        function SuccessFunction(data) {
            $("#myDiv").dialog("open");
            $("#myDiv2").html(data);
        }      
    </script>
}

No comments: