0

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(string 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>

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I added the id and changed to $("quoteForm[action~='GetQuote']")... and I am still being directed to another page
You need to move your <script> block below the <form>.
It didnt change :( ... See Edits
Change it to either #quoteForm or form[action~='GetQuote'], and read the documentation so that you can understand your mistake.
The change still gave the same result. I will check out the documentation and hopefully I can see the error
|
0

While SLaks answer did lead me in the right direction... I was missing the DOM call...

    $(document).ready(function() {
    $("form[action$='GetQuote']").submit(function() { 
    ...
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.