In this article I will explain with an example, how to return an object of Anonymous type from Web API 2 in ASP.Net MVC Razor.
This article will illustrate how to call a Web API Controller’s Action method that returns Anonymous type object using jQuery AJAX in ASP.Net MVC Razor.
Model
Following is a Model class named PersonModel with two properties i.e. Name and DateTime.
public class PersonModel
{
///<summary>
/// Gets or sets Name.
///</summary>
public string Name { get; set; }
///<summary>
/// Gets or sets DateTime.
///</summary>
public string DateTime { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Net;
using System.Net.Http;
Web API Controller
In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.
Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below.
Then give it a suitable name and click Add.
The next task is to register the Configuration for Web API in the Global.asax file so that the Web API is available for accessing on Web.
In order to do so open Global.asax file and add the following line.
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
Make sure you add it in the same order as shown below.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
The next step is to code the Web API Controller. The Web API Controller consists of a method named AjaxMethod which accepts an object of PersonModel and updates the DateTime property with the Current Date and Time and returns it back.
This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpPost attribute which signifies that the method will accept Http Post requests.
For returning an object of Anonymous type, the return type of the Action method is set to HttpResponseMessage class.
Finally the Anonymous type object is wrapped into a Response and then returned.
public class AjaxAPIController : ApiController
{
[Route("api/AjaxAPI/AjaxMethod")]
[HttpPost]
public HttpResponseMessage AjaxMethod(PersonModel person)
{
person.DateTime = DateTime.Now.ToString();
var response = new
{
Name = person.Name,
DateTime = DateTime.Now.ToString()
};
return Request.CreateResponse(HttpStatusCode.OK, person);
}
}
Controller
Now you will need to add one empty Controller along with a View. The View will be used for calling the Web API 2 Controller’s method using jQuery AJAX.
The Controller consists of an empty Action method which simply returns the View.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
View
Next step is to add an Empty View without Model for the Controller.
The View consists of an HTML TextBox element and a Button. The Button has been assigned a jQuery click event handler and when the Button is clicked a jQuery AJAX call is made to the Web API 2 Controller’s method.
The URL for the jQuery AJAX call is set to the Web API 2 Controller’s method i.e. /api/AjaxAPI/AjaxMethod. The value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<input type="text" id="txtName"/>
<input type="button" id="btnGet" value="Get Current Time"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnGet").click(function () {
var person = '{Name: "' + $("#txtName").val() + '" }';
$.ajax({
type: "POST",
url: "/api/AjaxAPI/AjaxMethod",
data: person,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.Name + ".\nCurrent Date and Time: " + response.DateTime);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
</body>
</html>
Screenshot
Downloads