Wednesday, January 25, 2012

pull in the HTML from an ASP.NET MVC partial into a view by way of jQuery AJAX

What if I had a controller like this?

using System.Web.Mvc;

namespace GenericPartialScrappingTest.Controllers

{

   public class LambController : Controller

   {

      public ActionResult Index()

      {

         return View();

      }

      

      public ActionResult _TwelveCells()

      {

         return PartialView();

      }

   }

}

 
 

The Index view looks like this:

<h2>Lamb Page</h2>

<p>This is a page with a partial:</p>

@Html.Partial("_TwelveCells")

 
 

The Index view pulls in this partial:

<table>

   <tr>

      <td>Mary</td>

      <td>had</td>

      <td>a</td>

   </tr>

   <tr>

      <td>lit-</td>

      <td>tell</td>

      <td>lamb</td>

   </tr>

   <tr>

      <td>lit-</td>

      <td>tell</td>

      <td>lamb</td>

   </tr>

   <tr>

      <td>lit-</td>

      <td>tell</td>

      <td>lamb</td>

   </tr>

</table>

 
 

In a different view, summoned by a different controller, I may pull in the partial by way of jQuery AJAX:

<h2>Home Page</h2>

<p>The div below should be filled by way of AJAX.</p>

<div id="whatever"></div>

<script type="text/javascript">

   var actionURL = '@Url.Action("_TwelveCells", "Lamb")';

   $.ajax({

      type: "POST",

      url: actionURL,

      data: "",

      success: function (r) {

         $("#whatever").html(r);

      },

      complete: function () {

         

      },

      error: function (req, status, error) {

         $("#whatever").html(error);

      }

   });

</script>

No comments:

Post a Comment