How to call web api method using jquery ajax in ASP.NET MVC 4

This tutorial will cover the following types of calling a web api method using jquery ajax.

  • Call a GET method without parameters
  • Call a GET method with a single parameter
  • Call a GET method with multiple paramerer
  • Call a POST method with multiple parameter

Before we start, Let me quickly created an api controller. Below is an api controller named “EmployeeController”, which will be used throughout all the examples.

public class EmployeeController : ApiController
{
    List<Employee> _employeeList = new List<Employee>
      {
          new Employee {FirstName = "Yasser", LastName = "Shaikh", Age = 24, DepartmentName = "S/W Engg"},
          new Employee {FirstName = "Roshan", LastName = "Punwani", Age = 25, DepartmentName = "SQL"},
          new Employee {FirstName = "Siddhesh", LastName = "Vasani", Age = 45, DepartmentName = "Sharepoint"},
          new Employee {FirstName = "Shival", LastName = "Sharma", Age = 36, DepartmentName = "Java Games"}
      };

    // all methods to come here.
}

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string DepartmentName { get; set; }
}

Ok, lets get started…

Type 1 : Call a GET method without parameters

Let us first create a GET method that does NOT accept any input parameters, this method will return a list of all the employees.

public List<Employee> GetAllEmployees()
{
   return _employeeList;
}

URL : http://localhost:1235/api/employee/

Using this url in the browser will give you the following output.

Web Api - GETWeb Api - GET

Jquery Ajax Call :

<script type="text/javascript">
$(document).ready(function () {
    var url = '/api/Employee';
    $.ajax({
        url: url,
        type: 'GET',
        success: function (result) {
            // use the result value here.
        }
    });
});
</script>

Console Output

Web Api - GET - Console log


Type 2 : Call a GET method with a single parameter

This method takes in the first name of the employee and returns a list of matching employees

public List<Employee> GetEmployeeByFirstName(string fname)
{
    return _employeeList.Where(m => m.FirstName == fname).ToList();
}

URL : http://localhost:1235/api/employee?fname=Yasser

Using this url in the browser will give you the following output.

Web Api - GET Single Param

Jquery Ajax Call :

<script type="text/javascript">
$(document).ready(function () {
    var fname = "Yasser"; // can be a value from a txtbox
    var url = '/api/Employee?fname=' + fname;
    $.ajax({
        url: url,
        type: 'GET',
        success: function (result) {
            // use the result value here.
        }
    });
});
</script>

Console Output

Web Api - GET Single Param - Console


Type 3 : Call a GET method with a multiple parameter

This method takes in the first name, last name and the age of the employee and returns a list of matching employees

public List<Employee> GetEmployeeByMultipleParams(string fname, string lname, int age)
{
   return _employeeList.Where(m => m.FirstName == fname && m.LastName == lname && m.Age == age).ToList();
}

URL : http://localhost:1235/api/employee?fname=Yasser&lname=Shaikh&age=24

Using this url in the browser will give you the following output.

Web Api - GET Multiple Param

Jquery Ajax Call :

<script type="text/javascript">
$(document).ready(function () {
    var fname = "Yasser"; // can be a value from a txtbox
    var lname = "Shaikh"; // can be a value from a txtbox
    var age = 24; // can be a value from a txtbox
    var url = '/api/Employee?fname=' + fname + "&lname=" + lname + "&age=" + age;
    $.ajax({
        url: url,
        type: 'GET',
        success: function (result) {
            // use the result value here.
        }
    });
});
</script>

Console Output

Web Api - GET Multiple Param - Console


Type 4 : Call a POST method with a multiple parameter

public bool PostEmployee(Employee employee)
{
    return _service.UpdateEmployee(employee);
}

Jquery Ajax Call :

<script type="text/javascript">
$(document).ready(function () {

    var url = '/api/Employee/PostEmployee';
    $.ajax({
        url: url,
        data: getData(),
        type: 'POST',
        contentType: "application/json",
        success: function (result) {
            console.log(result);
        }
    });

    function getData() {
        var employee = new Object();
        employee.FirstName = "Yasser R";
        employee.LastName = "Shaikh";
        employee.Age = "25";
        employee.DepartmentName = "S/W Engg";

        return JSON.stringify(employee);
    }
});

Hope this helps :)

Further Reading :

Net Tuts + : Building an ASP.NET MVC4 Application with EF and WebAPI

Web API : The Official Microsoft ASP.NET Site

Keyboard shortcuts for Outlook.com

Outlook.com ? What is it ?

Last week Microsoft launched new Outlook.com web mail service as a replacement to Hotmail.com. Every one likes the new Outlook.com layout which has a very clean and simple design.

List of shortcut keys for Outlook.com


Shortcut Key
ACTION
Delete Key Delete a message
Ctrl + N Create a new message
Ctrl+Enter Send a message
Ctrl+Shift+O  Open a message
Ctrl+Shift+P  Print a message
Ctrl+R Reply to a message
Ctrl+Shift+R Reply all to a message
Ctrl+Shift+F Forward a message
Ctrl+S Save a draft message
L Flag a message for follow up
C Categorize a message
Ctrl+Shift+J Mark a message as junk
Ctrl+Q Mark a message as read
Ctrl+U Mark a message as unread
Ctrl+. Move to a folder
Ctrl+, Open the previous message
Esc Close a message
/ Search your email messages
F7 Check spelling
S then A Select all
S then N Deselect all
F then I Go to the inbox
F then D Go to your drafts folder
F then S Go to your sent folder

But I’m more familiar with Gmail/Yahoo keyboard shortcuts

Incase you are more familiar with Gmail or Yahoo! keyboard shortcuts, you can use these in Outlook too, but you have to specify which shortcut keys are you going to use.

Keyboard Shortcuts Settings

Confused ? read this article by Microsoft to find out more : Keyboard shortcuts in Outlook.com

Hope this helps :)

Date.js conflicting with JqPlot, How to solve ?

Date.js has always been my first choice JavaScript Date Library for parsing, formatting and processing dates. Similary, I always use JqPlot to generate graphs (line, bar, bubbles, etc.)

But…

When these two plugins used together, it resulted into this problem. With virtually no alternative / quick fix. I had to settle with Moment.js.

Today with over a month of use with Moment.js, I am very happy with Moment.js. I had recently blogged about it here. Hope you found this helpful :)

How to make JqPlot responsive ?

jqPlot is a plotting and charting plugin for the jQuery Javascript framework. jqPlot produces beautiful line, bar and pie charts with many features.

To make JqPlot responsive we need to replot() the graph on change on window size. Here is how you should do it…

Using the replot() function this can be achieved, as done at this fiddle link. Read more on replot and redraw from here.

$(document).ready(function(){

    plot1 = $.jqplot ('chart', [[3,7,9,1,4,6,8,2,5]]);

    window.onresize = function(event) {
    plot1.replot();
    }
});

Hope this helps :)

How to show multiple Y- axis in jqplot

jqPlot is a plotting and charting plugin for the jQuery Javascript framework. jqPlot produces beautiful line, bar and pie charts with many features.

We can declare multiple Y-axis for a jqplot, like as shown below:

Code

$(document).ready(function(){
    var line1=[['11-01-2011',22], ['11-02-2011',3], ['11-03-2011',11], ['11-04-2011',33], ['11-05-2011',44], ['11-06-2011',14], ['11-07-2011',55]];
    var line2=[['11-01-2011',2121], ['11-02-2011',32323], ['11-03-2011',65656], ['11-04- 11',21212], ['11-05-2011',32323], ['11-06-2011',54544], ['11-07-2011',31230]];

    $.jqplot.config.enablePlugins = true;

    var plot1 = $.jqplot('chart1', [line1, line2], {
        title:'Revenue, Impressions vs Date',
        axes:{
        xaxis:{
            renderer:$.jqplot.DateAxisRenderer
        },
        yaxis:{
            autoscale:true,
            label: "Revenue"
        },
        y2axis:{
            autoscale:true,
            tickOptions:{showGridline:false},
            label: "Impressions"
        }

        },
        series:[{lineWidth:4}, {yaxis:'y2axis'}]
    });
});

Keyboard Shortcuts for WordPress HTML Editor

I always use HTML editor mode to writing each of my post, and below are the list of the shortcuts that I use.

Blockquote : Alt + SHIFT + q
Bold : Alt + SHIFT + b
Code : Alt + SHIFT + c
Insert date/time : Alt + SHIFT + s
Insert IMG URL : ALT-SHIFT-m
Italics : Alt + SHIFT + i
Line Break : SHIFT + Enter
Link : Alt + SHIFT + a
List Item (li) : Alt + SHIFT + l
Ordered List (ol) : Alt + SHIFT + o
Publish the Post : Alt + SHIFT + p
Read More : Alt + SHIFT + t
Redo : CTRL + y
Strikethrough : Alt + SHIFT + d
Undo : CTRL + z
Unordered List (ul) : Alt + SHIFT + u

Have I missed out something ? If that’s the case please let me know using the comment section.

Hope this helps.

How to read all errors from ModelState in ASP.NET MVC

ModelState plays an important role in client-side validation with ASP.NET MVC. Today I wanted to validate my model on server side and prepare a list of errors based on this validation.

I was able to do this using a little LINQ,

public static List<string> GetErrorListFromModelState(ModelStateDictionary modelState)  
{  
var query = from state in modelState.Values  
from error in state.Errors  
select error.ErrorMessage;

var errorList = query.ToList();  
return errorList;  
}

The above method returns a list of validation errors. Hope this helps :)

Further Reading :

How to get all Errors from asp.net mvc modelState?

How do I get the collection of Model State Errors in ASP.NET MVC?

Using jquery Validate.js with ASP.NET MVC 4

Validation.js is useful when performing client side validtions. Other than this jquery plugin, there is another one named jquery.validate.js comes in-built with the ASP.NET Web Project template.

Source Code

@model TestApp.Models.LoginModel

<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>  
<script src="../../Scripts/jquery.validate.js" type="text/javascript"></script>

<script>  
$(document).ready(function () {  
    $("#loginForm").validate();  
});  
</script>

<form id="loginForm">  
    <fieldset>  
    <ol>  
        <li>  
            @Html.LabelFor(m => m.UserName)  
            @Html.TextBoxFor(m => m.UserName, new { @class="required"})  
        </li>  
        <li>  
            @Html.LabelFor(m => m.Password)  
            @Html.PasswordFor(m => m.Password, new { @class = "required" })  
        </li>  
    </ol>

    <input type="submit" value="Submit"/>

    </fieldset>  
</form>

Below after few screenshots I have taken before and after the form submit.

Before

enter image description here

After hitting the submit button

enter image description here

Lets play around lil more with this, there are many other options that come with jquery.validate.js, that you should check out.

Source Code

@model TestApp.Models.LoginModel

<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>  
<script src="../../Scripts/jquery.validate.js" type="text/javascript"></script>

<script>  
$(document).ready(function () {  
    $("#registerForm").validate({    
        messages: {  
            UserName: {  
                required: "Eh ? empty username ?",  
                minLength: "At least 4 characters are necessary"  
            },  
            Password: {  
                required: "password missing"  
            },  
            Email: {  
                required: "please provide us your email, we promise we wont spam !",  
                email: "email id is not in correct format, eg: mail@yassershaikh.com"  
            }  
        }  
    });  
});  
</script>

<form id="registerForm">  
    <fieldset>  
    <ol>  
        <li>  
            @Html.LabelFor(m => m.UserName)  
            @Html.TextBoxFor(m => m.UserName, new { @class = "required", minLength = "4"})  
        </li>  
        <li>  
            @Html.LabelFor(m => m.Password)  
            @Html.PasswordFor(m => m.Password, new { @class = "required", minLength = "4" })  
        </li>  
        <li>  
            @Html.LabelFor(m => m.Email)  
            @Html.TextBoxFor(m => m.Email, new { @class = "required email" })  
        </li>  
    </ol>

    <input id="submitBtn" type="submit" value="Submit"/>

    </fieldset>  
</form>

Screengrab

enter image description here

There are loads of built-in Validation methods, check em out at docs.jquery.com/Plugins/Validation

Hope this helped you.

Happy Coding !

Further Reading

Using Ninject – Dependency Injection with ASP.NET Web API controllers

While setting up ninject with ASP.NET Web Api I encountered this error.

The error read "Type 'Api.Controllers.ABCController' does not have a default constructor". So after googling for while, I found out that there were many such problems reported.

Few of them are listed below, but none of the answers/workaround seemed to work for me. Until I bumped into this post.

Insert the following line of code into the CreateKernel() method before the call to the RegisterServices(kernel); is made.

GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);  

You will also need to use the below code, I prefer to have it defined in the same class.

public class NinjectResolver : NinjectScope, IDependencyResolver  
{  
    private IKernel _kernel;  
    public NinjectResolver(IKernel kernel) : base(kernel)  
    {  
        _kernel = kernel;  
    }  
    public IDependencyScope BeginScope()  
    {  
        return new NinjectScope(_kernel.BeginBlock());  
    }  
}

public class NinjectScope : IDependencyScope  
{  
    protected IResolutionRoot resolutionRoot;  
    public NinjectScope(IResolutionRoot kernel)  
    {  
        resolutionRoot = kernel;  
    }  
    public object GetService(Type serviceType)  
    {  
        IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);  
        return resolutionRoot.Resolve(request).SingleOrDefault();  
    }  
    public IEnumerable<object> GetServices(Type serviceType)  
    {  
        IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);  
        return resolutionRoot.Resolve(request).ToList();  
    }  
    public void Dispose()  
    {  
        IDisposable disposable = (IDisposable)resolutionRoot;  
        if (disposable != null) disposable.Dispose();  
        resolutionRoot = null;  
    }  
}

Run it, and it should work. This worked for me, I hope it does for you too. Please leave a comment in case the error persists. (AND leave a comment if it works)

:)