Quantcast
Channel: Jonathan Creamer's Dev Diary » jQuery
Viewing all articles
Browse latest Browse all 4

ASP.NET MVC 3 jQuery Ajax Views

$
0
0

So today I decided to experiment with some Ajax and jQuery stuff in an MVC3 application. It’s pretty cool the way things all tie together using jQuery to hit an MVC controller and return some data and has hundreds if not thousands of uses in an application. So here is what I did to get some simple data posted from a form in a Razor view to a controller and return some data.

First off, you have to create an action in whatever controller you are going to use that the Ajax will hit.


public ActionResult Info(string name)
{
     return Json("Well howdy " + name + "!");
}

The URL for Ajax to hit is going to be {YourController}/Info. Next up is the stuff for the view.

<script src="../../Scripts/Home.js" type="text/javascript"></script>
@using (Html.BeginForm())
{
     @Html.TextArea("txtField", new { id = "txtField" });
}
<div id="results">
</div>

And finally Home.js. Just FYI in order to use intellisense in external Javascript files, you have to have that reference path in the comments. Just take it out before you deploy the code.


//**  This is necessary if for jQuery intellisense **//
/// <reference path="jquery-1.4.4.min.js" />

$(document).ready(function () {
     var txt = $("#txtField");
     txt.keyup(function(){
          $.post("/Home/Info", {
               name: $(this).val()
          }, function (response) {
               $("#results").html(response);
          });
     });
});


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images