Hello Friends, In last session, I did cover some of the basic concepts of asp.net mvc. So let us put them in to practice. We are taking example of customer registration form in the tutorial. As we move forward we will be adding more functionalities to it.
Setup MVC Project
Fire up VS2013 and create new project : Asp.net web application and then select the template as MVC.Files Setup
Once project is created, we need to add model, view and controller required for customer registration form.
- Right click on controller and add new controller :CustomerController.
- Right click on Model and add new class : CustomerModel
- Right click on 'View/Customer' and add new view :Customer
Design Model, View and Controller
Let us create customer registration form add some html mark-up to our view. We need to use some of the MVC helper methods to create form and textbox controls to accept inputs from end user.
Below are the helper methods that I use to build input elements for this form.
Below are the helper methods that I use to build input elements for this form.
- Html.BeginForm – This method creates new form for submitting customer data to customer controller. Method accepts Action method and controller name as input parameter. In this case: Action method is: SaveCustomer and controller name: Customer.
- Html.LabelFor – Creates labels for every customer property that needs be displayed in customer registration form
- Html.TextBoxFor- Creates Textbox field for entering customer data like first name, last name, phone number etc.
- Html.ValidationSummary: As we defined data constraints for the customer model, if any of the constraints gets failed, then validation errors will be thrown. ValidationSummary method displays all the validation errors that were reported during model validation.
Customer registration view :
@model MVCApplication.Models.CustomerModel
@{
ViewBag.Title = "Customer";
Layout = "~/Views/Shared/_Layout.cshtml";
}fh
@using (Html.BeginForm("SaveCustomer", "Customer", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
<h4>Create a new Customer.</h4>
<hr />
@Html.ValidationSummary("", new { @class = "text-danger" })
<p style="font-weight:bold" >@ViewBag.SucessMessage</p>
<div class="form-group">
@Html.LabelFor(m => m.FirstName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.LastName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.LastName, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.EmailId, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.EmailId, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.PhoneNumber, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.PhoneNumber, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
|
Designing Model
Let us design our customer model. The model holds basic customer information, which gets supplied by end user while creating customer.
In order to validate what gets passed from user input to the model, we have added annotation attributes: Required and ReqularExpression. (This is explained in the previous article).
CustomerModel.cs:
public class CustomerModel
{
[Required(ErrorMessage = "Please enter your First Name",
AllowEmptyStrings = false)]
public string FirstName { get; set; }
public string LastName { get; set; }
[Required(ErrorMessage = "Email Id cannot be blank", AllowEmptyStrings = false)]
[RegularExpression(@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$",
ErrorMessage = "Your email doesnt look good")]
public string EmailId { get; set; }
public string PhoneNumber { get; set; }
}
|
Implementing Action methods
Let us add new action method: SaveCustomer for registering new customer.- The method should take input argument of type CustomerModel.
- Add HttpPost attribute to ensure that method is invoked only via http post request.
- Add validation to check if incoming customer data is good. This can be done by calling the inbuilt method "ModelState.IsValid". The method validates all the business rules defined on the model and returns true or false.
- If ModelState.IsValid method return true, then customer data can be saved in the database by calling service. Integration with service is explained in the upcoming article.
CustomerController.cs:
public class CustomerController : Controller
{
// GET: Customer
public ActionResult Index()
{
return View("Customer");
}
[HttpPost]
public ActionResult SaveCustomer(CustomerModel customer)
{
if (ModelState.IsValid)
{
//TODO: Call service to save customer
ViewBag.SucessMessage = "Customer Registration was
successful";
}
return View("Customer");
}
|
Customize Routing Configuration
public class RouteConfig
{
public static void RegisterRoutes(RouteCollectionroutes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Customer", action = "Index",
id = UrlParameter.Optional }
);
}
}
|
Testing customer Registration Form
Happing coding,
MK
No comments:
Post a Comment