Why does my submit button fail to trigger Javascript MVC?
I have a simple code from a book and the code should display data from my controller in the "results" span. What am I missing?
Controller...
public string GetQuote(strin开发者_JS百科g symbol)
{
if (symbol.Trim() != "")
return "99";
else
return "Sorry";
}
ASPX...
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Index</h2>
<%using (Html.BeginForm("GetQuote","Stocks", new { id = "quoteForm" })) { %>
Symbol:
<%= Html.TextBox("symbol") %>
<input type="submit" />
<span id="results"></span>
<% } %>
<p><i><%=DateTime.Now.ToLongTimeString() %></i></p>
<script type="text/javascript">
$("form[action~='GetQuote']").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(response) {
$("#results").html(response);
});
return false;
});
</script>
You selector only matches <form>
elements where the action
parameter ends with GetQuote
.
You need to change it to form[action~='GetQuote']
to match <form>
elements where the action
parameter contains GetQuote
.
Alternatively, you can add an ID to your form, like this:
using (Html.BeginForm("GetQuote","Stocks", new { id = "quoteForm" }))
and change the selector to #quoteForm
.
While SLaks answer did lead me in the right direction... I was missing the DOM call...
$(document).ready(function() {
$("form[action$='GetQuote']").submit(function() {
...
});
精彩评论