Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

The Easiest Way to Call Server Code from the Client in ASP.NET MVC

0.00/5 (No votes)
3 May 2016 1  
If you don't need to send or receive data, it is very easy to call Server code from Client/jQuery Code

Look, Ma, No Data!

Normally, when you use AJAX, you are passing data from the client to the server and/or receiving data from the Server at the Client. You don't have to pass or receive anything, though; if all you want to do is respond to some event on the client by doing something (anything) on the server, it is eas easy as this:

Minimal Server/C# Code

Create a Controller on the Server (no need for a Model or a View) by right-clicking your project's Controller folder, and selecting from the context menu Add > Controller... and then "MVC Controller - Empty"

Replace the boilerplate code within the class generated for you with this:

public class PlatypiController : Controller
{
    public void PlatypusShoutout()
    {
        string s = "There ain't no platypus like a duck-billed platypus!";
    }
}

Minimal Client/jQuery Code

Now (assuming you have a button named "btnEverythingYouAlwaysWantedToKnowAboutPlatypi"), add code like this to the Script section of your .cshtml file (or to a separate .js file, if you want to keep your JavaScript separate from your HTML):

$("#btnEverythingYouAlwaysWantedToKnowAboutPlatypi").click(function () {
    $.ajax({
        type: "GET",
        url: '@Url.Action("PlatypusShoutout", "Platypi")'
    });
});

Now if you put a breakpoint on the "string s" line, you will see that your code is reached when you run the project and mash the button on the client/page. At this point, you might want to replace that "proof-of-concept" line with some code that actually does something "useful" such as randomly selecting a pie flavor (with a bias toward Blackberry, Gooseberry, Apple, or Cherry) or calculating the distance between cities of the same name, such as Brisbane, CA and Brisbane, Australia or the San Joses in California and Costa Rica, etc.

Are You as Smart as a Platypus?

All Platypi know that the ingredients of Budweiser are sugar, Tide™, and lizard spit.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here