?
Solved

Jquery Ajax request to MVC Web API

Posted on 2014-04-12
8
Medium Priority
?
1,023 Views
Last Modified: 2014-04-22
I want to make a Jquery Ajax request to MVC Web API. I successfully made it work just fine by making the call this way:

GlobalContoller.cs
[HttpGet]
        public DataTable Select(string TableName, string Fields, string Condition)
        {
            DataTable dt = new DataTable();
            dt = BalAccess.Select(TableName, Fields, Condition);

            int dtCount = dt.Rows.Count;

            if (dtCount > 0)
            {
                ConvertNullToEmptyString(dt);

            }
            
            return dt;
        }

Open in new window



WebApiConfig.cs
config.Routes.MapHttpRoute(
                name: "SelectApi",
                routeTemplate: "api/{controller}/{action}/{TableName}/{Fields}/{Condition}",
                defaults: new { controller = "Global", action = "Select", TableName = RouteParameter.Optional, Fields = RouteParameter.Optional, Condition = RouteParameter.Optional }
            );

Open in new window


main.js
    var request = jQuery.ajax({
        url: "../api/global/Select/Users/first,last/1=1",
        type: "get",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        timeout: 5000
    });

Open in new window


The code above works fine
The problem is that I want to call the action method with making the parameter separate in the ajax data option instead of the url option.
However I would like my ajax call to look like this

var TableName = "Users";
    var Fields = "first,last";
    var Condition = "1=1";

    var JsonText = JSON.stringify({ TableName: TableName, Fields: Fields, Condition: Condition });

    // Read the data from our database backend.....
    var request = jQuery.ajax({
        url: "../api/global/Select",
        type: "get",
        data: JsonText,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        timeout: 5000
    });

Open in new window

0
Comment
Question by:quest_capital
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
8 Comments
 
LVL 23

Assisted Solution

by:Ioannis Paraskevopoulos
Ioannis Paraskevopoulos earned 1000 total points
ID: 39997263
Hi,

I've been trying to do similar calls and there are some issues with Web API. The easiest way by far is the following:

1. Install Json.Net

Get this library which is also available in NuGet.

2. Create a Request Class

Create a class that will hold your input. In your Example this could be:
public class SelectArgs
{
    public string TableName {get; set;}
    public string Fields {get; set;}
    public string Condition {get; set;}
}

Open in new window


3. Use Json.NET to use this class

You should make your method need a JObject as an argument, that you will internally translate to your SelectArgs class:

[HttpPost]
public DataTable Select(JObject selectArgs)
{
     var obj = selectArgs.ToObject<SelectArgs>();
     DataTable dt = new DataTable();
     dt = BalAccess.Select(obj.TableName, obj.Fields, obj.Condition);

     int dtCount = dt.Rows.Count;

     if (dtCount > 0)
     {
           ConvertNullToEmptyString(dt);

     }
            
     return dt;
}

Open in new window


4. Make your call

Now your javascript call to Web API should work. Make sure you change the method from get to post. You will also need to change your route (or add a new one). You might not need any changes to the route since you are defining the properties as optional.

Good luck,
Giannis
0
 

Author Comment

by:quest_capital
ID: 39997444
jyparask

Thx for the post but how would I change the route can you give an example?

Like this?:
config.Routes.MapHttpRoute(
                name: "SelectApi",
                routeTemplate: "api/{controller}/{action}/{selectArgs}",
                defaults: new { controller = "Global", action = "Select", TableName = RouteParameter.Optional }
            );

Open in new window

0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 39997466
Hi,

First of all, you might not need to change it (have you tried it as is?)

2. Since it is a Post method, you won't add anything to your URL, so it should be:

config.Routes.MapHttpRoute(
                name: "SelectApi",
                routeTemplate: "api/{controller}/{action}",
                defaults: new { controller = "Global", action = "Select"}
            );

Open in new window


Then in your js try:

    var TableName = "Users";
    var Fields = "first,last";
    var Condition = "1=1";
    var request = jQuery.ajax({
        url: "../api/global/Select",/Users/first,last/1=1",
        type: "Post",
        dataType: "json",
        data: { TableName: TableName, Fields: Fields, Condition: Condition }
        contentType: "application/json; charset=utf-8",
        timeout: 5000
    });

Open in new window


Giannis
0
The Orion Papers

Are you interested in becoming an AWS Certified Solutions Architect?

Discover a new interactive way of training for the exam.

 

Author Comment

by:quest_capital
ID: 40004539
jyparask

I add the json library in my file.
In your example below ToObject shows an error.
[HttpPost]
public DataTable Select(JObject selectArgs)
{
     var obj = selectArgs.ToObject<SelectArgs>();
     DataTable dt = new DataTable();
     dt = BalAccess.Select(obj.TableName, obj.Fields, obj.Condition);

     int dtCount = dt.Rows.Count;

     if (dtCount > 0)
     {
           ConvertNullToEmptyString(dt);

     }
            
     return dt;
}

Open in new window

0
 

Author Comment

by:quest_capital
ID: 40004589
and JObject shows an error
0
 

Accepted Solution

by:
quest_capital earned 0 total points
ID: 40006765
Based on jyparask suggestion of creating a class for the parameters helped in solving my problem. Here is the final code that worked:

controller.aspx
public class pSelect
        {
            public string TableName { get; set; }
            public string Fields { get; set; }
            public string Condition { get; set; }
        }

........

[HttpPost]
        [Route("api/global/Select")]
        public DataTable Select(pSelect v)
        {
            DataTable dt = new DataTable();
            dt = BalAccess.Select(v.TableName, v.Fields, v.Condition);

            int dtCount = dt.Rows.Count;

            if (dtCount > 0)
            {
                ConvertNullToEmptyString(dt);

            }
            
            return dt;
        }

Open in new window



I removed the routing in the WebApiConfig and placed it in the controller page.
0
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 40006789
Sorry, i never got notified of your updates, so i just saw them...

If you are still interested, what was the error with JObject? Maybe you were not having the appropriate usings. Did you get JSon.Net from NuGet?

Giannis
0
 

Author Closing Comment

by:quest_capital
ID: 40014363
na
0

Featured Post

WordPress Tutorial 3: Plugins, Themes, and Widgets

The three most common changes you will make to your website involve the look (themes), the functionality (plugins), and modular elements (widgets).

In this article we will briefly define each again, and give you directions on how to install them.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses
Course of the Month9 days, 8 hours left to enroll

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question