How do I get Ajax form submissions to work in ASP.net MVC?
-
11-09-2019 - |
Question
I'm very new to the AJAX and Javascript world and I'm trying to implement Scott Hanselman's example of form submission to update part of a page. I have copied his example almost word-for-word and I can't seem to get it to work. When I click the submit button the controller action is called successfully but the result is rendered in the browser as a new page, instead of updating just the span that I specified in the Ajax form.
Here is my view code:
<asp:Content ID="indexHead" ContentPlaceHolderID="head" runat="server">
<title>Home Page</title>
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<% using (Ajax.BeginForm("TestAction", new AjaxOptions { UpdateTargetId = "target" }))
{ %>
<%= Html.TextBox("TextBox")%>
<input type="submit" value="Submit" />
<span id="target" />
<% } %>
</asp:Content>
And my controller action:
public string TestAction(string TextBox)
{
return TextBox;
}
And I have included the following lines in the master page
<script src="../../Scripts/MicrosoftMvcAjax.debug.js"type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
But all it seems to do is call the action and render the result as a new page, instead of updating the target span. Here are some small screenshots to illustrate what's happening.
Screenshot 1 http://martindoms.com/scr1.JPG
Screenshot 2 http://martindoms.com/scr2.JPG
Any ideas?
Solution
You have the javascript include in your master page in the wrong order. Reorder so that MicrosoftAjax.js is included first of the three and it will work.
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
OTHER TIPS
Just throwing some ideas out there...
http://www.asp.net/learn/MVC/tutorial-33-cs.aspx
Your controller action is in a class defined like so?
public class MyController : Controller
Apparently the name of the class has to end with the word controller.