Friday, July 11, 2014

Use "html" as the data type instead of "json" when pulling in an ASP.NET MVC partial with jQuery's .ajax.

This is a view I have in an application I am making. It will populate partials into a div inside itself.

<div id="view"></div>
<input type="hidden" value="@ViewBag.CurrentView" id="whereami" />
<script language="javascript">
   $(function() {
      getView();
   });
   function getView(currentView) {
      $("#view").html("");
      if (currentView) {
         $("#whereami").val(currentView);
      } else {
         currentView = $("#whereami").val();
      }
      $.ajax({
         type: "GET",
         url: "/" + currentView,
         data: 'html',
         success: function(result) {
            $("#view").html(result);
         }
      });
   }
</script>

 
 

A controller I might hit to get a partial looks like this:

using System.Web.Mvc;
namespace Whatever.Controllers
{
   public class FooController : Controller
   {
      public ActionResult Index()
      {
         return PartialView("Foo");
      }
   }
}

No comments:

Post a Comment