Developing asp.net MVC5 web application


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.
  1. 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.
  2. Html.LabelFor – Creates labels for every customer property that needs be displayed in customer registration form
  3. Html.TextBoxFor- Creates Textbox field for entering customer data like first name, last name, phone number etc.
  4. 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 { getset; }
        public string LastName { getset; }

        [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 { getset; }

        public string PhoneNumber { getset; }
    }



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

    As we have added customer controller. Let us go ahead and customize route that exist under RoutingConfig file. This is basically required to setup the customer controller as default controller. You may be eager to know more details about routing,so i have created separate session3 for this topic.

     
    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


     Ok!. Now it’s the time for testing the application and verify if it works as expected. The form looks good (not very fancy, but we can do that by adding bit more css). Lets click on register button without entering basic information. The application validates inputs and throws validation error back.


    Let me try again by entering correct information this time. Hurrah, it worked. we can add few more views to display and edit customer information,which I will cover up in upcoming articles.



    In this article, I explained how we can build a simple mvc5 application with customer registration form as example. Go through my article on entity framework to understand how we can integrate a mvc application with back end databases.

    Happing coding,
    MK

    No comments: