rigamonk rigamonk - 5 months ago 23
Javascript Question

Passing values from javascript to an MVC controller function when button is clicked

I have an Html Button and a razor EditFor textbox. this is to add something to a database. However, i want this particular button to call a function to get information from a webservice (IMDB) in order to fill in the rest of the information. Here is what I have for the Razor Portion:

<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>


I want to take this value and when the 'IMDB' button is clicked, i want to call the service to get the JSON. Heres my button:

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" id="IMDB" value="IMDB" class="btn btn-default" onclick="AjaxDisplayString();" />
</div>
</div>


And here is my javascript on the page:

<script>
function AjaxDisplayString() {
$.ajax({
url: @Url.Action("CallIMDB"),
method: 'GET',
success: function(data) { alert(data); }
});
}

</script>


This never calls my controller function. The page does nothing. Here is my MVC controller function that is supposed to be called

public ActionResult CallIMDB(string title)
{
var client = new WebClient();
var json = client.DownloadString("http://www.omdbapi.com/?t=" + title.Replace(' ', '+') + "&y=&plot=short&r=json");
var search = System.Web.Helpers.Json.Decode(json);
return search;
}


So, to sum up. I am trying to take the Title value from my razor for editor field and pass it into the controller function to get the JSON back from IMDB web service. However, the page does nothing, and the controller function is never called.

Answer

In order to take the "title" value, change your script like this:

<script>
    function AjaxDisplayString() {
        var action = '@Url.Action("CallIMDB")'; // action must be between quotes
        var title = $("#Title").val(); // get the "Title" from input text

        var url = action + "?title=" + title; // get the complete url with route values

        $.ajax({
            url: url,
            method: 'GET',
            success: function(data) { alert(data); }
        });
    }

</script>