Sunday, March 17, 2013

NerdDinner Tutorial in Visual Studio 2012

I’ve been going through Scott Guthrie’s NerdDinner Tutorial.  It’s been very educational for me.  However, it’s written in Visual Studio 2010 with C# and .aspx pages.  As I’ve been going through it, I’ve been using Visual Studio 2012, Visual Basic, and Razor.  During the process, I’ve occasionally had to wrestle to get things working right.  The most challenging has been step 10, AJAX Enabling RSVPs Accepts.

There’s nothing particularly complicated in this step, but I had to do a lot of dancing to get it to work right.  When I did I found myself thinking, “why exactly did that take so long?”  In any case, I thought I’d mention the major obstacle I encountered and what I did to get around it, in case anyone else is struggling with the same thing.

Here’s the code that was the problem:

 <%= Ajax.ActionLink( "RSVP for this event",  
"Register", "RSVP",
new { id=Model.DinnerID },
new AjaxOptions { UpdateTargetId="rsvpmsg"}) %>

In order to get the AJAX to work, Guthrie says to include these libraries:

 <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>  
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

My first question was, if these libraries should be included to get Ajax.ActionLinks to work, why aren’t they included in the Scripts folder by default?  The answer is, they’re not needed in VS 2012 (at least for this application), since jquery.unobtrusive-ajax, will handle it, and that library is included in web projects by default, and is included in the jqueryval bundle in the BundleConfig file.

So, those Microsoft AJAX libraries don’t need to be included.  Instead, the Details view needs this:

 @Section Scripts  
End Section

But even with that change, the Ajax.ActionLink was not working.  It was doing a GET rather than a POST.  So, I had to change it to this:

       @Ajax.ActionLink("RSVP for this event - AJAX",  
New With {.id = Model.DinnerId},
New AjaxOptions With {.UpdateTargetId = "rsvpmsg", .HttpMethod= "Post"})

With that, the Ajax.Actionlink works as expected.

Here’s a stray observation.  When the code was not working, clicking the “Register” link was behaving differently between Chrome and IE.  Chrome would give me a “resource not found” error page, while in IE nothing would happen.  I wonder if it’s not a good idea to always create a view to handle an ActionLink, for cases when there’s a JavaScript issue, even one that’s not the developer’s fault (e.g. a user’s machine having a cached .js file that’s out-of-date or not compatible with other .js files).

No comments:

Post a Comment