How to Create a Data Entry Form in ASP.NET MVC
by Editor GetCodeSnippet • January 2, 2016 • Microsoft .NET C# (C-Sharp), Microsoft ASP.NET MVC • 0 Comments
Suppose we have online book store and an online customer wants to purchase a book. Now there should be a link in our web page like “Add Book in Cart”. After adding this link, customer should have a form to fill the book’s details. We as a .NET MVC developer will achieve this task in the following given way.
First of all, we create a book class in our Model folder and define the properties keeping in view the form’s details about the book. The book class is given below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BooksCollection.Models { public class Book { public string Authorname { get; set; } public string Title { get; set; } public string Publisher { get; set; } public DateTime PublishDate { get; set; } } } |
Then in the main page of our online book store, we have to create a link like “Add Book in Cart”. Code is given below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@{ ViewBag.Title = "Home Page"; } <html> <head> <title>Book</title> </head> <body> <h3>Purchase a book</h3> <div> Click the link below to add a book </div> <div><b>@Html.ActionLink("Add Book in Cart", "AddBook")</b></div> </body> </html> |
Output of the above code will be
Now when the customer click on the ‘Add Book in Cart’ link, it will redirect customers to ‘AddBook’ View where customer can fill the book’s details and add to cart. Below the AddBook.cshtml code;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
@model BooksCollection.Models.Book @{ ViewBag.Title = "AddBook"; } <html> <head> <title>Add Book</title> </head> <body> <h3>Form to add book's Detail</h3> <div> @using (Html.BeginForm()) { <div>Name :</div><div>@Html.TextBoxFor(m => Model.Authorname)</div> <div>Title: </div><div>@Html.TextBoxFor(m => Model.Title)</div> <div>Publisher: </div><div>@Html.TextBoxFor(m => Model.Publisher)</div> <div>Publisher Date: </div><div>@Html.TextBoxFor(m => Model.PublishDate)</div> <div><input type="submit" name="Add Book" /></div> } </div> </body> </html> |
We use razor syntax for creating a form . First line of code’ @model BooksCollection.Models.Book ‘ shows its a strong type view. @using (BeginForm()) is used to render a form that will be handled by the controller action method.We use @html.TextBoxFor() to create a text box , not used @html.Texbox() because AddBook view is strongly typed view and we have to use the model’s property in the text box method. The output is given below;
