Introduction
In this tip, you can learn about how to use WebApi with MVC and jquery. I have defined get
, post
, put
and delete
methods using model
class to use it in jquery at client side and MVC controller.
About WebApi
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
We already know about WCF services and web services that both are soap based services and they use HTTP as the transport level protocol. That means they use HTTP protocol just to tunnel the soap messages across the internet. But all clients are not handled to suitable the soap messages. SOAP messages are internally XML and handling XML which might be complicated for some clients. And the best example non soap based client is JQUERY. Now to overcome this problem we introduced WCF rest services. If you are conversant with REST, please go through WCF REST services site and first learn it there. REST is an architectural style which says to use the existing features of the web in a more efficient and simpler way. If you want to know about the features and to learn them, those are HTTP verbs like GET
, POST
, PUT
and DELETE
. In REST, every stuff is unique to identify, not always in XML for communication you can pass XML, JSON so on. Use this feature for this we are calling HTTP rest service.
For use of WCF rest service, it requires lots of configuration settings which is a bit complicated. The main intention behind services is building service oriented architecture not to support REST. Now Microsoft simplified this and finally it came with the solution, created part of ASP.NET called ASP.NET Web API. It is part of ASP.NET technology for creating REST services.
MVC with API
With MVC 4 application with selection of Web API Template, this includes a sample web API call ValuesController
. Here you will find lots of features which are the same as MVC. It means not exactly the same but its code patterns are similar. If you are not an MVC developer, these things may be difficult for you, otherwise it's very easy to understand.
Let's discuss something about this. In MVC, there is an added MVC Controller whereas in web API, there is an added API controller. In API controller, action methods are HTTP verbs like Get
, Post
, Put
and Delete
even we can overload this methods.
Let's discuss about another feature - that's RouteConfig.cs file:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Person",
action = "Index", id = UrlParameter.Optional }
);
}
}
Let's discuss about MVC Routes how MVC is implemented with Web API. You will get App_Start folder and open it. When request comes to MVC, it takes the URL and passes through its three segments. The first name is controller, it finds controller by its name. Next is action then it finds the methods with this name. And also, we have default id with option UrlParameter
. Just like this, we have WebApiConfig.cs file:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Just like this in WebApi
default name is DefaultApi
. Just to keep separate with MVC routes web API routes template defined first is API. We can change it to customerapi
, facebookapi
so on as per our requirement. Next is controller and id option RouteParameter
. The main thing is that it doesn't have action here, we only have HTTP methods depending on client requirements. If it is a get
request, the get
method will call and post
request, then post
method will call and so on.
Controller
Let's create a Person
class inside model folder.
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public DateTime DOB { get; set; }
}
public class PersonEntities : DbContext
{
public DbSet<person> Persons { get; set; }
}
Using Get Method of Web API
Default Api name in MVC is ValuesController. I have changed instead of returning string
changed to person
list. If you will see there are two Get methods in Values Api, One with parameter another with id parameter. For list we are calling without parameter to get all person details. See the following details
public class ValuesController : ApiController
{
PersonEntities db = new PersonEntities();
public IEnumerable<person> Get()
{
return db.Persons.ToList();
}
}
I have commented the default return values. I have also dded PersonalEntities
where I have defined it in model
class. When you will run the application, browse through the ../api/Values/ you will get data with XML in chrome browser. You can get JSON representation of data from request of get
method. For this, I have designed it in Index2
VIEW
page. This is just as content negotiation. Depending on the client request, it returns the data. When client says XML, it returns XML and JSON even say we return our own custom format like visiting card, class or anything.
$(document).ready(function () {
$.ajax({
url: "http://localhost:49493/api/Values",
type: "Get",
success: function (data) {
for (var i = 0; i < data.length; i++) {
$("
<tr></tr>
<td></td>
" + data[i].Name + "</td>
<td></td>
" + data[i].Address + "</td>
<td></td>
" + data[i].DOB + "</td></tr>").appendTo("#tbPerson");
}
},
error: function (msg) { alert(msg); }
});
});
In this above code, I have collected JSON data by the code of JSON format and designed it to our HTML page. One of the things we can show as MVC format by the call of Web API get method where you will get complete information to view the downloaded project. if you will run http://localhost:49493/api/Values in chrome browser then get to see like below image. It will return HTTP XML values.
For the second case Get with parameter. And that one used in Detail page for a particular person information. It's done in Details ActionResult see the following code.
public ActionResult Details(int id)
{
Person person = db.Get(id);
return View(person);
}
In the above method we are calling Api Get method with parameter. This is also a process we can call WebApi method from action result.
Using Post Method of Web API
Now, we will write a code which will consume the web API by the way of JQuery and MVC. Now I am writing a post method in Web API to insert data.
public void Post(List<string> val)
{
try
{
Person obj = new Person();
obj.Name = val[0];
obj.Address = val[1];
obj.DOB = Convert.ToDateTime(val[2]);
db.Persons.Add(obj);
db.SaveChanges();
}
catch (Exception) { }
}
Now our main purpose to use Web API in client side using MVC. For this, I have added a script in MVC using jquery link. You will get to see to post data using JQuery with MVC. For this, I have coded it into create.cshtml. You will get to see below:
$(document).ready(function () {
$("#submit").click(function () {
var name = $("#Name").val();
var address = $("#Address").val();
var dob = $("#DOB").val();
$.ajax({
url: "http://localhost:49493/api/Values",
type: "Post",
data: JSON.stringify([name, address, dob]),
contentType: 'application/json; charset=utf-8',
success: function (data) { },
error: function () { alert('error'); }
});
});
});
If you will see inside the downloaded source code it's done in two way now one using json webApi and another ActionResult to WebApi.
Using Put Method of Web API
This is a part to discussion Put method of WebApi. And this is using for updated the source code. It's done in two way one using Json to WebApi and another is ActionResult to WebApi. First one I am going to describe Json to web Api. So in Edit.cshtml page I have defined in jquery
<script>
$(document).ready(function () {
$("#EditApi").click(function () {
var id = $("#ID").val();
var name = $("#Name").val();
var address = $("#Address").val();
var dob = $("#DOB").val();
$.ajax({
url: "http://localhost:49493/api/Values",
type: "Put",
data: JSON.stringify([name, address, dob, id]),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert('Updated Successfully');
window.location.href = "../Index";
},
error: function (msg) { alert(msg); }
});
});
});
</script>
First if we will see we are getting ID from a hidden input, that's defined in top
@Html.HiddenFor(model => model.ID)
And collection all input value using json val(). Here Main purpose is that to call put method. Now we will send list of values to put method. So json data is using JSON.stringify()[....] type. I am defined one method Put in WebApi which is following below.
public void Put(List<string> val)
{
try
{
int id = Convert.ToInt32(val[3]);
Person obj = db.Persons.Find(id);
obj.Name = val[0];
obj.Address = val[1];
obj.DOB = Convert.ToDateTime(val[2]);
db.Persons.Add(obj);
db.Entry(obj).State = System.Data.EntityState.Modified;
db.SaveChanges();
}
catch (Exception) { }
}
</string>
This is pattern to use json to WebApi in MVC. If you will see one more format that can be done in ActionResult where I have post the data from edit.cshtml and accessing post Edit ActionResult where I am calling Api method on following ways.
[HttpPost]
public ActionResult Edit(int id, Person obj)
{
try
{
db.Put(id, obj);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Using Delete Method of Web API
Same way we have done also Delete operation in WebApi method. Now It's done on both of way. First I am going to express Json to WebApi. See the code in Delete.cshtml page.
<script>
$(document).ready(function () {
$("#deleteApi").click(function () {
var id = $("#ID").val();
$.ajax({
url: "http://localhost:49493/api/Values/" + id,
type: "Delete",
success: function (data) {
alert('Deleted Successfully');
window.location.href = "../Index";
},
error: function (msg) { alert(msg); }
});
});
});
</script>
But in delete case If we will check in Api method there is one parameter only. For this we have to send parameter in MVC format with URL. So I have added the id parameter values in url, and type is Delete. Then it will call the delete method of WebApi where Api method as following below.
public void Delete(int id)
{
Person obj = db.Persons.Find(id);
db.Persons.Remove(obj);
db.SaveChanges();
}
for the Action Result I am accessing same webapi method here.
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
db.Delete(id);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Conclusion
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
References