Tuesday, March 13, 2012

Forms in ASP.net MVC 3

The form representation is different in ASP.net MVC as compared to ASP.net.
there is no straight form tag that we were using in other version than MVC.
To create forms we need to user Html Helpers

HTML.Begin Form() method is used to define the form.

@using(HTML.BeginForm()){

// here you can define your form
// I am taking example of a product form



Product Name

     
@Html.TextBox("ProductName")

     
Product Description

     
@Html.TextArea("ProductDescription")

     



}


on the other hand to handle this form request on post.
you need to add the following code in your product controller :

   // I have created a product model in productsModel namespace where I have defined the
  // class for product..
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
                MvcAppTutorial.Models.Product myProduct = new Models.Product();
                myProduct.ProductName = collection["ProductName"];
                myProduct.ProductDesc = collection["ProductDescription"];
                ViewBag.ErrorMessage = "Data Saved";
                return View();
            }
            catch
            {
                return View();
            }
        }

Next I will show you how to add validations to the form..