Use jQuery.post to submit to ASP.NET MVC Actions

Recently, Microsoft announced that jQuery will be shipping with future versions of Visual Studio.  In fact, today the ASP.NET MVC bits already ship with jQuery.  ASP.NET MVC is extremely friendly with jQuery. 

One of the things that ASP.NET MVC gives you over web forms is an easy way to expose actions to the client.  Here's where AJAX using jQuery really shines.  In the past if you wanted to initiate some server side action using JavaScript, you'd need to expose a web service of some kind and then call into your server from there.  With ASP.NET MVC you can simply submit a post to an action via a URL and you're off.

For example, I might have the following action called 'DoSomething' on my 'Thing' controller:

public ActionResult DoSomething(int thingId, string thingName, 
        DateTime thingDate) {

        var db = new ThingEntities();
        var thing = (from Thing t in db.Things
                                      where t.ID == thingId,
                                      select t).First<Thing>();

        thing.Name = thingName;
        thing.ThingDate = thingDate;

        db.SaveChanges(true);

return Content("true");
}

Calling this method from JavaScript becomes almost trivial using the jQuery.post method:

$.post("/Thing/DoSomething", { thingId: 7, thingName: 'New Thing', thingDate: '1/1/2008' }, function(data) { alert(data); });

So the post method has three parameters:

  1. The URL of the action to post to. 
  2. An object comprising the data to send with the post. 
  3. A callback method which fires when the request returns. 

It's as simple as that.  So now making calls back to your server from JavaScript is as easy as writing a controller action that takes simple types as parameters.  There are several different jQuery AJAX methods to chose from and obviously some more advanced things that you can do, but as you can see the basics are pretty simple.

Category: ASP.NET MVC, jQuery 2 comments »

2 Responses to “Use jQuery.post to submit to ASP.NET MVC Actions”

  1. Rohith

    Very Interesting .Nice idea.Is There any chance to publish the source code please.May Thanks

  2. James

    Really like this! Simple and easy to implement. Only problem is support for users without JavaScript. I supposed something like a submit button in s would be the solution. Thanks for sharing.


Leave a Reply



Back to top