markneustadt.com

Ajax forms and PartialViews opening in a new page

Why can’t this just work the way it’s supposed to out of the box?

So here’s today’s dilemma (which I’ve solved exactly once for each project I’ve done because once it’s done you don’t have to redo it which makes me think ‘gee… maybe it should be this way to start off with’).  When you have a form on your page and want to submit it and get a result via Ajax the results are being displayed on a new page, not in the output div you specified.

Out of the box, Microsoft’s MVC is full of a lot of wonderful stuff.  There are built in helpers to help you write a form that will submit via Ajax and get a result back.  It’s pretty cool.  The problem is that they sorta forgot to include the necessary pieces to actually make it all work.

  • Open the Package Manager Console in Visual Studio.  TOOLS > Library Package Manager > Package Manager Console
  • Add jquery.unobtrusive-ajax.js using this command:
     PM> Install-Package jQuery.Ajax.Unobtrusive
  • Add MicrosoftAjax.js using this command:
     PM> Install-Package MicrosoftAjax
  • Add MicrosoftMvcAjax.js using this command:
     PM> Install-Package MicrosoftMvcAjax.Mvc5
  • Update your App_Start/BundleConfig.cs file such that it includes an entry for the ajax libraries in the right order:
     bundles.Add(new ScriptBundle("~/bundles/ajax").Include(     "~/Scripts/jquery.unobtrusive-ajax.js", "~/Scripts/MicrosoftAjax.js", 
    "~/Scripts/MicrosoftMvcAjax.js"));
  • Finally… update your _Layout.cshtml file so that the includes will render properly

    @Scripts.Render("~/bundles/bootstrap", "~/bundles/jquery", "~/bundles/ajax")
  • Make sure jQuery is in there as well.  For some reason it wasn’t added either. 

When all is said and done, when you do a “View Source” on your page, you should have at least these four script tags.

<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/MicrosoftAjax.debug.js"></script>
<script src="/Scripts/MicrosoftMvcAjax.debug.js"></script>

Now, you should be able to refresh your page and try your form again.

Scroll To Top