Solved

Jquery Ajax request to MVC Web API

Posted on 2014-04-12
8
990 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
  • 5
  • 3
8 Comments
 
LVL 23

Assisted Solution

by:Ioannis Paraskevopoulos
Ioannis Paraskevopoulos earned 250 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
 

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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…

746 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now