Поделиться через


Walkthrough: Adding ASP.NET AJAX Scripting to an MVC Project

ASP.NET AJAX enables a Web application to retrieve data from the server asynchronously and to update parts of the existing page. This improves the user experience by making the Web application more responsive.

This walkthrough shows how to get started with adding ASP.NET AJAX functionality to an ASP.NET MVC application.

A Visual Studio project with source code is available to accompany this topic: Download.

Prerequisites

In order to complete this walkthrough, you will need:

  • Microsoft Visual Studio 2008. You cannot use Microsoft Visual Web Developer Express for this walkthrough.

  • The ASP.NET MVC 2 framework. If you have installed Visual Studio 2010, the ASP.NET MVC 2 is already installed on your computer. To download the most up-to-date version of the framework, see the ASP.NET MVC download page.

Creating a New MVC Project

To begin, you will create a new ASP.NET MVC project. To keep this walkthrough simple, you will not create the test project that is an option for ASP.NET MVC projects. For more information about how to create an MVC test project, see Walkthrough: Creating a Basic MVC Project with Unit Tests in Visual Studio.

To create a new MVC project

  1. On the File menu, click New Project.

  2. In the New Project dialog box under Project types, expand either Visual Basic or Visual C#, and then click Web.

  3. Under Visual Studio installed templates, select ASP.NET MVC Web Application.

  4. In the Name box, type MvcAjaxApplication.

  5. In the Location box, enter the name of the project folder.

  6. Select Create directory for solution.

  7. Click OK.

  8. In the Create Test Project dialog box, select No, do not create a unit test project.

    Note

    If you are using the Visual Studio 2008 Standard, the Create Unit Test Project dialog box is not displayed. Instead, the new MVC application project is generated without a test project.

  9. Click OK.

    The new MVC application project is generated.

Referencing the ASP.NET AJAX Script Libraries

Support for the client functionality of ASP.NET AJAX is in two script libraries: MicrosoftAjax.js and MicrosoftMvcAjax.js. The release version and the debug version of these scripts are located in the project's Scripts folder. Before you can access these libraries in client script, you must add library references to the MVC views in the current project.

To reference the ASP.NET AJAX script libraries

  1. In Solution Explorer, expand the Views folder, and then expand the Shared folder.

  2. Double-click the Site.Master file to open it.

  3. Add the following markup at the end of the head element:

    <script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>" 
        type="text/javascript"></script>  
    <script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>" 
        type="text/javascript"></script>
    
        <script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>" 
            type="text/javascript"></script>  
        <script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>" 
            type="text/javascript"></script>
    

    Alternatively, you can drag these files from Solution Explorer onto the Site.Master view, and this code will be added for you.

Adding Action Methods to the HomeController Class

Next you will add two action methods that can be called asynchronously from client script. The GetStatus method just returns a status of "OK" and the current time. The UpdateForm method receives input from an HTML form and returns a message that includes the current time.

To add the action methods to the HomeController class

  1. In Solution Explorer, expand the Controllers folder, and then double-click the HomeController class to open it.

  2. Add the following code after the About method.

    Public Function GetStatus() As String
        Return "Status OK at " + DateTime.Now.ToLongTimeString()
    End Function
    
    Public Function UpdateForm(ByVal textBox1 As String) As String
        If textBox1 <> "Enter text" Then
            Return "You entered: """ + textBox1.ToString() + """ at " + DateTime.Now.ToLongTimeString()
        End If
    
        Return [String].Empty
    End Function
    
    public string GetStatus()
    {
        return "Status OK at " + DateTime.Now.ToLongTimeString();
    }
    
    public string UpdateForm(string textBox1)
    {
        if (textBox1 != "Enter text")
        {
            return "You entered: \"" + textBox1.ToString() + "\" at " +
                DateTime.Now.ToLongTimeString();
        }
    
        return String.Empty;
    }
    

Redefining the Index Page

Finally, you will replace the content of the Index.aspx page, which is added automatically to the Visual Studio project for ASP.NET MVC. The new Index.aspx page displays the time that the page is rendered, a status message that has a link for updating the message asynchronously, and a form for submitting a text string.

To redefine the Index page

  1. In Solution Explorer, expand the Views folder, expand the Home folder, and then open the Index view.

  2. Replace the content of the Content control with the following markup:

    <h2><%= Html.Encode(ViewData("Message")) %></h2>
    <p>
      Page Rendered: <%= DateTime.Now.ToLongTimeString() %>
    </p>
    <span id="status">No Status</span>
    <br />   
    <%=Ajax.ActionLink("Update Status", "GetStatus", New AjaxOptions With {.UpdateTargetId = "status"})%>
    <br /><br />
    <% Using (Ajax.BeginForm("UpdateForm", New AjaxOptions With {.UpdateTargetId = "textEntered"}))%>
      <%= Html.TextBox("textBox1","Enter text")%>  
      <input type="submit" value="Submit"/>
      <br />
      <span id="textEntered">Nothing Entered</span>
    <% End Using%>
    
    <h2><%= Html.Encode(ViewData["Message"]) %></h2>
    <p>
        Page Rendered: <%= DateTime.Now.ToLongTimeString() %>
    </p>
    <span id="status">No Status</span>
    <br />   
    <%= Ajax.ActionLink("Update Status", "GetStatus", new AjaxOptions{UpdateTargetId="status" }) %>
    <br /><br />
    <% using(Ajax.BeginForm("UpdateForm", new AjaxOptions{UpdateTargetId="textEntered"})) { %>
      <%= Html.TextBox("textBox1","Enter text")%>  
      <input type="submit" value="Submit"/><br />
      <span id="textEntered">Nothing Entered</span>
    <% } %>
    

    In the example, an asynchronous link is created by calling the Ajax.ActionLink method. This method has several overrides. In this example, it accepts three parameters. The first parameter is the text for the link. The second parameter is the MVC action method to call. The third parameter is an AjaxOptions object that defines the intended purpose of the call. In this case, the code will update the DOM element whose ID is status.

    The form is defined by using the Ajax.Form method, which also has several overrides. In this example, it accepts two parameters. The first parameter is the action method to call. The second parameter is another AjaxOptions object, which specifies that the DOM element whose ID is textEntered is to be updated.

Testing the Application

Now you can run the application and see how it works.

To run the MVC application

  1. Press CTRL+F5.

    The page displays the time that it was rendered.

  2. Click the Update Status link.

    The status message is updated with the time that it was updated. Notice that only the status message was updated.

  3. Enter text in the text box and then click the Submit button.

    A message displays the text that you entered and the time it was entered. Once again, notice that only the form was processed.

See Also

Tasks

Walkthrough: Creating a Basic MVC Project with Unit Tests in Visual Studio

Other Resources

ASP.NET MVC 2