共用方式為


ASP.NET MVC Framework, Ajax, & jQuery

(archived from my old blog from my pre-MS days)

I've seen a few examples trying to show how to combine the MVC Framework and Ajax.  There are even a couple that show you how to use jQuery with MVC.  However, they sometimes leave out a couple of details - like properly passing parameters to the Ajax controller and returning information from the controller - both are trivial if you've done it before, but if not... well, an example helps.

Let's have a view/page that insults you - that's always fun.  As a bonus, you're insulted via Ajax using jQuery to call an MVC Framework controller.  Let's start with the Controller, as all good MVC practitioners should:

 namespace JqueryTest1.Controllers{    using System.Web.Mvc;    public class HomeController : Controller    {        [ControllerAction]        public void Index() { RenderView("InsultMe"); }        [ControllerAction]        public void InsultMe() { RenderView("InsultMe"); }        [ControllerAction]        public void InsultViaAjax(string who, string what)        {            // normally we'd return something more sophisticated than plain text,            // but, hey!  It's just an example.            Response.Write("Your " + who + " wears " + what + "!" );        }    }}

It's pretty simple - a couple of controller actions to handle the default view and the "Insult Me" view, which are the same thing in this instance, and an "InsultViaAjax" action that takes its parameters from the Request["xxx"] collections - very nice.  Then my simple Ajax controller puts together an original insult from the parameters and writes it back out to the response stream.

Next we have the Site.Master page, which we've just modified to contain the references to the jQuery scripts.  In order to have some useful intellisense we add a second reference to a "dummy" jQuery script, which contains only the information required for jQuery intellisense, basically empty shells with XML documentation comments.  You can get the jQuery intellisense script from here.

 <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs"     Inherits="JqueryTest1.Views.Layouts.Site" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="https://www.w3.org/1999/xhtml"><head runat="server">    <title>My Sample MVC Application</title>    <link href="../../Content/Site.css" rel="stylesheet" type="text/css"  />
     <script src="../../Content/javascript/jquery-1.2.3.js" type="text/javascript" />        <!-- this is a little trickery to get intellisense to work well for jQuery -->    <asp:Placeholder runat="server" visible="false">        <script src="../../Content/javascript/jquery-1.2.3-intellisense.js"             type="text/javascript" />    </asp:Placeholder>
 </head><body>    <div id="inner">            <div id="header">            <h1>An Insulting Sample MVC Application</h1>        </div>                <div id="maincontent">            <asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server">            </asp:ContentPlaceHolder>        </div>      </div></body></html>

And finally the view itself, InsultMe.aspx.

 <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"     AutoEventWireup="true" CodeBehind="InsultMe.aspx.cs"     Inherits="JqueryTest1.Views.Home.InsultMe" Title="Insulting Example" %><asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder"     runat="server"><form id="insult-form" action="NA">    <fieldset>        <legend>Insult Me</legend>        <label for="who">Your relation:</label>        <input type="text" id="who" name="who" value="mamma" />        <br />        <label for="what">Footwear:</label>        <input type="text" id="what" name="what" value="combat boots" />        <br />        <input type="submit" id="insult-me" name="insult-me"             value="Insult me now" />    </fieldset></form><script type="text/javascript">    $(document).ready(function () { // when the document is all ready,        $("#insult-form").submit(function() { // hijack the form's submission,             $.post(   // and replace it with an Ajax call                 '/home/InsultViaAjax',                 $("#insult-form").serialize(),                function(returnVal) {                     alert('Here it comes: ' + returnVal);                 });             return false; // stop the actual html form submission        });                // a little eye-candy to hide the form until the ajax call is complete        jQuery().ajaxStart(function() {             $("#insult-form").fadeOut("slow");        });                jQuery().ajaxStop(function() {            $("#insult-form").fadeIn("fast");        });    });</script>    </asp:Content>

Do you want to watch it all happening? Love those morbid details? Then check out FireBug, an add-on to FireFox that makes it easy to set breakpoints and step through the JavaScript code.

Technorati Tags: jQuery,Ajax,ASP.NET