Click here to Skip to main content
15,504,286 members
Articles / Web Development / HTML
Article
Posted 24 Jul 2014

Stats

257.1K views
6.8K downloads
52 bookmarked

Do GET, POST, PUT, DELETE in ASP.NET MVC with Jquery Ajax

Rate me:
Please Sign up or sign in to vote.
4.67/5 (35 votes)
24 Jul 2014CPOL3 min read
Do GET, POST, PUT, DELETE in ASP.NET MVC with Jquery Ajax

Introduction

In ASP.NET MVC, we have seen http verbs like HttpGet, HttpPost, HttpPut and HttpDelete. Here, we will see how we can use these words in actions, what do these words mean, and how we can use jquery ajax calls for such http verb enable actions.

Why Use HttpVerbs?

Let's examine these actions:

UrlResponse()

  1. Is accessible using browser url
  2. It can also be used for Ajax calls
JavaScript
public JsonResult UrlResponse()     //accessible using Url
{
    return Json(new { Name = "UrlResponse", Response = "Response from Get", 
      Date = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") }, JsonRequestBehavior.AllowGet);
}

TypedResponse()

  1. It can only be usable using Ajax calls using (type: "GET")
  2. If trying to access using browser url, it would throw an error
JavaScript
[HttpGet]
public JsonResult TypedResponse()    //error if try to access using Url
{
    return Json(new { Name = "TypedResponse", Response = "Response from Get", 
       Date = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") }, JsonRequestBehavior.AllowGet);
}

MultipleTypedResponse()

  1. If trying to access using browser url, it would throw an error
  2. It can only be usable using Ajax calls using (type: "GET"/"POST")
JavaScript
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
//or [AcceptVerbs("GET","POST")]
public JsonResult MultipleTypedResponse()
{
    return Json(new { Name = "MultipleTypedResponse", Response = "Response from Get", 
       Date = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") }, JsonRequestBehavior.AllowGet);
}

Now let’s see how we can use http verbed actions in MVC, and Jquery Ajax calls using $.ajax objects together. But there are some concerns with:

  1. How to specify a particular action for Ajax call.

    At url attribute, use specify the controller and actions as /{controller}/{action} pattern:

    url: '/User/Create',
    url: '/User/Get/20',
  2. How to specify the http verb in Ajax call:

    At the type attribute with values GET/ POST/ PUT/ DELETE of the Ajax object:

    JavaScript
    type: "POST",
    JavaScript
    type: "GET",
  3. How to pass parameters to that action if needed.
    • At data attribute, we specify the data to be passed to a particular action.
      JavaScript
      data: JSON.stringify({ user: { name: 'Rintu', email: 'Rintu@gmial.com' } }),
      JavaScript
      data: { name: 'Rintu', email: 'Rintu@gmial.com' },
    • For GET requests, we can also specify the data at the url attribute, but we need to work with route configurations too. (Here, we are avoiding things, concerning rout config).
    JavaScript
    url: '/User/Get/20',
  4. Where to find the response data.

    At the success attribute, we will get the response data.

    JavaScript
    success: function (data) {
        alert(data);
    },
  5. Is there any error?

    At the error attribute, we will get error detail, if any found at the server end:

    JavaScript
    error: function (xhr) {
        alert('error');
    }

HttpGet

MVC Action

JavaScript
// GET: /User/Get/5
[HttpGet]
public JsonResult Get(int id)
{
    return Json("Response from Get", JsonRequestBehavior.AllowGet);
}

Ajax Call

  1. passing value of id as url: '/User/Get/20'
  2. no use of data attr at the Ajax object
JavaScript
/*GET*/
$.ajax({
    url: '/User/Get/20',
    dataType: "json",
    type: "GET",
    contentType: 'application/json; charset=utf-8',
    async: true,
    processData: false,
    cache: false,
    success: function (data) {
        alert(data);
    },
    error: function (xhr) {
        alert('error');
    }
});

HttpPost

MVC Action

JavaScript
// POST: /User/Create
[HttpPost]
public JsonResult Create(User user)
{
    return Json("Response from Create");
}

Ajax Call

Data is passed to action using the data attribute of the Ajax object:

JavaScript
/*POST*/
$.ajax({
    url: '/User/Create',
    dataType: "json",
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ user: { name: 'Rintu', email: 'Rintu@gmial.com' } }),
    async: true,
    processData: false,
    cache: false,
    success: function (data) {
        alert(data);
    },
    error: function (xhr) {
        alert('error');
    }
})

HttpPut

MVC Action

JavaScript
// PUT: /User/Edit
[HttpPut]
public JsonResult Edit(int id, User user)
{
    return Json("Response from Edit");
}

Ajax Call

JavaScript
/*PUT*/
$.ajax({
    url: '/User/Edit',
    dataType: "json",
    type: "PUT",
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ id: 100, user: {name: 'Rintu', email: 'Rintu@gmial.com'} }),
    async: true,
    processData: false,
    cache: false,
    success: function (data) {
        alert(data);
    },
    error: function (xhr) {
        alert('error');
    }
});

HttpDelete

MVC Action

JavaScript
// DELETE: /User/Delete
[HttpDelete]
public JsonResult Delete(int id)
{
    return Json("Response from Delete");
}

Ajax Call

JavaScript
/*DELETE*/
$.ajax({
    url: '/User/Delete',
    dataType: "json",
    type: "DELETE",
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({id: 20}),
    async: true,
    processData: false,
    cache: false,
    success: function (data) {
        alert(data);
    },
    error: function (xhr) {
        alert('error');
    }
});

Well, they all worked fine, but there are some interesting things too. Let’s just talk about them too.

Let's Take Some Closer Looks for GETs

When we are working with httpGet verbed actions, we may face concerns like:

Pass Data as Objects Rather Than JSON.stringify(object)

Action

JavaScript
// GET: /User/Contains
[HttpGet]   //use or not works same
public JsonResult Contains(string name, string email)
{
    return Json("Response from Contains", JsonRequestBehavior.AllowGet);
}

Ajax Call

JavaScript
/*GET*/
$.ajax({
    url: '/User/Contains',
    dataType: "json",
    type: "GET",
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',    //replace /json to the urlenoded
    data: { name: 'Rintu', email: 'Rintu@gmial.com' },          // data is not json
    async: true,
    processData: true,                                                  //important to use it as true
    cache: false,
    success: function (data) {
        alert(data);
    },
    error: function (xhr) {
        alert('error');
    }
});

Let’s find some differences with the previous HttpGet verb use.

At the old one, we have used:

  1. url: '/User/Get/20'
  2. There was no data attribute at the Ajax object.

At this one, we have used:

  1. url: '/User/Create'
  2. data: { name: 'Rintu', email: 'Rintu@gmial.com' }

And this would work just fine.

What if We Try to Pass Values Using Both Url and Data?

Action

JavaScript
// GET: /User/Find/1/30 or
// GET: /User/Find
[HttpGet]
public JsonResult Find(int pageNo, int pageSize, User user)
{
    return Json("Response from Find", JsonRequestBehavior.AllowGet);
}

Ajax Call

JavaScript
/*GET*/
$.ajax({
    url: '/User/Find/3/5',
    dataType: "json",
    type: "GET",
    contentType: 'application/json; charset=utf-8',
    //pageNo: 2, pageSize: 20 would not be posted to the action,
    //it would be 3 and 5 as we specified it at ajax url
    //and user would be null
    data: { pageNo: 2, pageSize: 60, user: { name: 'Rintu', email: 'Rintu@gmial.com' } },
    async: true,
    processData: false,
    cache: false,
    success: function (data) {
        alert(data);
    },
    error: function (xhr) {
        alert('error');
    }
})

At action pageNo and pageSize would be 1 and 30 rather than 2 and 20, as priority of the url data pass is higher.

This type of "GET" requests with data in url, helps in action overloading too. In such case, we have to be aware of the route configurations.

Yes, there is another problem with the user object here, and we are going to discuss about it too.

Who to Pass Complex Objects Using "GET" to Actions?

Action: Here, we need to pass pageNo, pageSize and user object detail (Id, Name, Email):

JavaScript
// GET: /User/Find/1/30 or
// GET: /User/Find
[HttpGet]
public JsonResult Find(int pageNo, int pageSize, User user)
{
    var value = Request.QueryString["user"];
    /*here we will not get user, beacuse mvc doesn't work like that*/
    /*solution 1: rather than an object, use all properties of user object as parms
      Find(int pageNo, int pageSize, long userId, string userName...)
    */
    /*solution 2: use httppost, which is the most proper for the job*/
    return Json("Response from Find", JsonRequestBehavior.AllowGet);
}

Try url value pass, but how to pass the user object in url? Let’s try something like:
Result at action, pageNo: 3, pageSize: 5, user: null

JavaScript
/*GET*/
$.ajax({
    url: '/User/Find/3/5',
    dataType: "json",
    type: "GET",
    contentType: 'application/json; charset=utf-8',
    data: { user: { name: 'Rintu', email: 'Rintu@gmial.com' } },       
    async: true,
    processData: false,
    cache: false,
    success: function (data) {
        alert(data);
    },
    error: function (xhr) {
        alert('error');
    }
});

Try value pass as object, like:

Result at action, pageNo: 2, pageSize: 20, user: null

JavaScript
/*GET*/
$.ajax({
    url: '/User/Find',
    dataType: "json",
    type: "GET",
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    data: { pageNo: 2, pageSize: 20, user: { name: 'Rintu', email: 'Rintu@gmial.com' } },
    async: true,
    processData: true,
    cache: false,
    success: function (data) {
        alert(data);
    },
    error: function (xhr) {
        alert('error');
    }
});

In both cases, we were unable to pass to the values of user object.

So how can we pass those values all together?

Solution 1: Rather than an object, use all properties of user object as parms

C#
Find(int pageNo, int pageSize, long userId, string userName...)

Solution 2: Use httppost and POST, which is the most appropriate for the job

Limitations

  1. Yes, there could be something that I misunderstood or mispresented. So if you find anything, just let me know.
  2. All of these examples are not fully operational in real time projects yet, but they have been used at prototype levels.

Find the Visual Studio 2012 solution of MVC4 project in the attachment.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Prince Daniel4-Oct-17 3:58
Prince Daniel4-Oct-17 3:58 
QuestionTypedResponse can be accessed from URL Pin
Senal19-May-15 2:41
Senal19-May-15 2:41 
Questiongood articles. Pin
Bhavesh Patel1-May-15 19:45
Bhavesh Patel1-May-15 19:45 
GeneralMy vote of 5 Pin
FranCastillo9-Oct-14 0:55
FranCastillo9-Oct-14 0:55 
GeneralRe: My vote of 5 Pin
DiponRoy23-Mar-15 9:58
DiponRoy23-Mar-15 9:58 
QuestionAbout this Post Pin
Raju Hasan3-Aug-14 1:42
professionalRaju Hasan3-Aug-14 1:42 
AnswerRe: About this Post Pin
DiponRoy23-Mar-15 9:59
DiponRoy23-Mar-15 9:59 
QuestionRe: About this Post Pin
YASHWANTH S17-Jan-22 5:33
YASHWANTH S17-Jan-22 5:33 
QuestionMy vote of 5 too Pin
Member 107815271-Aug-14 16:17
Member 107815271-Aug-14 16:17 
AnswerRe: My vote of 5 too Pin
DiponRoy23-Mar-15 9:59
DiponRoy23-Mar-15 9:59 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun25-Jul-14 1:32
Humayun Kabir Mamun25-Jul-14 1:32 
GeneralRe: My vote of 5 Pin
DiponRoy25-Jul-14 1:37
DiponRoy25-Jul-14 1:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.