Send data to MVC C# controller using jQuery Ajax

In this article, I am going to explain how we can easily send data from Front-end using Ajax to the controller in C# and getting data from controller back to front end.If you will create basic MVC C# project in Visual Studio 2015 , in scripts folder there must be a jquery-1.10.2 file (or it can be another jquery version) , we are going to use it in this article.

What is jQuery?

jQuery is a fast, small, feature-rich, and lightweight, "write less, do more", JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

The purpose of jQuery is to make it much easier to use JavaScript on your website.

jQuery Syntax

A jQuery statement typically starts with the dollar sign ($) and ends with a semicolon (;).

In jQuery, the dollar sign ($) is just an alias for jQuery. Let's consider the following example code which demonstrates the most basic statement of the jQuery.

//Start of script
<script type="text/javascript">
// jQuery calls are placed inside $(document).ready function so that it can run after loading document completly
$(document).ready(function(){
//jquery Code to be executed
alert("Hello World!");
});
</script>

jQuery Ajax

Now let's get started with basics of Ajax, and what is does.

AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology help us to load data from the server without a browser page refresh.]

Example:-Call a local script on the server /api/getWeather with the query parameter zipcode=97201 and replace the element #weather-temp's html with the returned text.

I have created a function which is called when user click's on Button with Id 'Authenticate', inside it, we have ajax call to server URL, please check comments to understand it line by line.

NOTE : contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.

Step 2: Create ActionMethod in Controller

[HttpPost] //type of request if it [HttpGet], you can leave it blank, JsonResult of data type to be returned
public JsonResult GetAuthToken(string username, string password)
{
try
{
//
using (var context = new DatabaseConnectionEntities())
{
// Do something like save details in database
context.SaveChanges();
}
//return data with a new Object and Msg in it as Success
return Json(new { Msg = "Sucess" });
}
Catch(exception e)
{
//return data with a new Object and Msg in it as Error/Error details
return Json(new { Msg = "Error" });
}
}

In the above controller Method we are accepting the values as username, password, and after performing some function on it, returning the success or error msg on the front end.

Call $().Load('url') for simple Get request

The jQuery load() method is a simple, but powerful AJAX method.The load() method loads data from a server and puts the returned data into the selected elementSyntax :-

$(selector).load(URL,data,callback);

We can use it to Load partial view in MVC C#, for example, we can have jquery code like this