views:

73

answers:

2

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  A: 

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.

SLaks
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>`.
SLaks
It didnt change :( ... See Edits
Change it to either `#quoteForm` **or** `form[action~='GetQuote']`, and read the [documentation](http://api.jquery.com/category/selectors/) so that you can understand your mistake.
SLaks
The change still gave the same result. I will check out the documentation and hopefully I can see the error
You missed the #
SLaks
I am still not able to get thru using the javascript... Ajax.BeginForm() gets the job done, but I will need more freedom than what is allowed on that approach.
A: 

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

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