views:

1315

answers:

1

I'm starting to learn ASP.Net MVC (the release candidate), and I'm having a little trouble. I might just be being picky, but I thought I'd ask.

I want to use the built-in (extended) ASP.Net Ajax methods to make a call to my controller, called "GetNames," that returns a JsonResult object. I've seen examples that use the $.getJSON() jQuery method, but I would instead prefer to do something like this:

 <%using ( Ajax.BeginForm("GetNames", new AjaxOptions() { OnSuccess = "GetNamesSuccess", OnBegin = "GetNamesBegin", OnComplete = "GetNamesComplte", OnFailure = "GetNamesFailure" } ) ) { %>

    <%=Html.TextBox("DummyData") %>
    <input type=submit />

<% } %>

<script type="text/javascript">
    function GetNamesSuccess()
    {
        alert("Success");
    }

    function GetNamesBegin()
    {
        alert("Begin");
    }

    function GetNamesComplete()
    {
        alert("Complete");   
    }

    function GetNamesFailure()
    {
        alert("Failure");
    }        
</script>

When I click the Submit button, I get none of the alerts, and I get prompted to download a file containing the text of Json object, which I believe indicates that at least the controller method is working fine. But that's not the intended behavior for me... Ideally, Ajax.BeginForm would set it up such that the Json object would get passed to either the OnSuccess or the OnComplete method.

Is there a way to accomplish that?

+3  A: 

Have you included both the MicrosoftAjax.js and MicrosoftMvcAjax.js javascript files in your view page? It sounds to me like it is actually posting the form instead of using Ajax. I've had this problem when I was missing the MicrosoftAjax.js include because the Ajax postback failed due to missing javascript classes and thus it invoked the normal form post.

On a related note, you should check to see if the request is Ajax or not in the controller and return a ViewResult (or Redirect) instead of Json if it's not. If someone has javascript turned off or you have errors on your page you want it to gracefully degrade and handle it as a normal postback rather than return Json.

tvanfosson
Looks like you're right! I assumed that the Ajax helper methods I was using would automatically add any needed javascript files to the response. Doh! Thanks.
Moskie