Introduction
This is my fourth article on Web API 2. This article explains the Web API in a HTML page. This is the most simple task to consume in HTML using JavaScript. In my previous articles we saw MVC, then Web Forms.
- Getting Started With ASP.Net Web API 2: Day 1
- Getting Started With ASP.Net Web API 2: Day 2
- Getting Started With ASP.Net Web API 2: Day 3
In this article we will learn how to create an ASP.NET Web API 2 endpoint capable of handling HTML forms. We can create a controller action that accepts a model and that model will help to get and set the form value and ASP.NET Web API to do the model binding for us.
- public class FormController : ApiController
- {
- public UserModel Post(FormDataCollection form)
- {
- //process form...
- var user = new UserModel
- {
- Email = form["Email"],
- Name = form["Name"],
- Address = form["Address"],
- Address2 = form["Address2"],
- Mobile = form["Mobile"]
- };
- return user;
- }
- }
System.Net.Http.Formatting.FormDataCollection is used to handle the form as we need.
When we submit the data form URL with the Web API it uses MediaTypeFormatter to extract data from the HttpRequestMessage and pass it to the relevant action selected to the handle the request. By default, the Web API reads the body of the request only once, so when using a model to bind to form data, that model should encapsulate all of the form fields. It is not possible to pass some of the fields as part of the request body and some in the URL and expect the framework to try to automatically reconcile them into a single model.
Prerequisites
There are the following things we need to use when developing a Web API 2 Application under the Web Form.
- Visual Studio 2013
- ASP.NET Web API
Getting Started
In this section we will follow some section and these are:
- Create ASP.NET Web Form
- Add Web API 2 Controller
Create ASP.NET Web API with MVC
There are some basic procedures to follow, when creating a Web API along with MVC using Visual Studio 2013, we need to also check the Web API button, as we are showing in the following images.
Step 1
Open the Visual Studio 2013 and click New Project.
Step 2
Select the ASP.NET Web Application and provide a nice name for the project.

Step 3
Select the Web API template and click the OK button.

Step 4
Add a UserModel class to the model where we define all the necessary fields. In the following image, I have defined some fields like name, email, Address and Mobile number.

Step 5
Add the Form controller. When we create the Form Controller be sure we have used a model and the System.Net.Http.Formatting namesapce.

Step 6
Add the User Controller.

Step 7
Now make a HTML design. Click on View and select Home folder, then we will get the default Index.Cshtml (Razaor) page.




Arweb AroshanzamirPosted Feb 9, 2015, 3:45 PM
nice one.. thanks sir