Thursday 20 February 2014

BeginForm Helper in MVC 3 Razor

  • We create form to post user's input to the server, ore render the same data from the server on the UI.
  • BeginForm HTML Helper is use to create form on the UI. The HTML helper renders the form tag as markup.
  • The BeginForm helper method has various overloads. 
  • In this article we will see how we can use this helper to render form element.
Example:

Controller:
        //Renders the View with form
        public ActionResult HtmlForm()
        {
            return View();
        }

        //Form is posted to this method.
        [HttpPost]
        public ActionResult HtmlForm(CustomerViewModel model)
        {
            return View();
        }
    

We have used two Action methods for this example. The first method renders the view. The second method is the one where form is posted. The second method has HTTPPost attribute denoting it is the form post and accepts an object of CustomerViewModel class.

ViewModel:

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;

        namespace HtmlHelpers.ViewModel
        {
            public class CustomerViewModel
            {
                public int CustomerID { get; set; }

                public string Name { get; set; }

                public string City { get; set; }

                public string Email { get; set; }
            }
        }
    

The above class our ViewModel. The properties defined in this view model are rendered inside the form tag.

View:

        @model HtmlHelpers.ViewModel.CustomerViewModel

        @{
            ViewBag.Title = "HtmlForm";
        }

        <h2>HtmlForm</h2>


        @using (Html.BeginForm("HtmlForm", "Home"))
        {
            @Html.EditorForModel("CustomerViewModel")
            <input type="submit" id="SubmitButton" value="Submit" />
        }
    

We have used BeginForm helper in the above view. The BeginForm helper outputs both the opening <form> and the closing </form>. The helper emits the opening tag during the call to BeginForm, and the call returns an object implementing IDisposable. When execution reaches the closing curly brace of the using satement in the view, the helper emits the closing tag with implicit call to Dispose. The using trick makes the code simpler and elegant.
                                              The submit button posts the form to the HtmlForm action method of Home controller.

Screenshot:



By default BeginForm helper renders the form with POST form method. The BeginForm helper has overload which accepts a FormMethod type parameter using which we can specify POST or GET as type of form method.

Form with GET:

    @using (Html.BeginForm("HtmlForm", "Home", FormMethod.Get))
    {
        @Html.EditorForModel("CustomerViewModel")
        <input type="submit" id="SubmitButton" value="Submit" />
    }

The third parameter specifies whether the FormMethod is POST or GET. By default form is rendered with POST form method. The HtmlForm action method is called when the form is rendered with GET FormMethod.

We can also pass parameter to the Action method using GET. 



    @using (Html.BeginForm("HtmlForm", "Home", FormMethod.Get))
    {
        @Html.EditorForModel("CustomerViewModel")
        <input type="submit" id="SubmitButton" value="Submit" />
    }
    
Controller:
        [HttpGet]
        public ActionResult HtmlForm(int? CustomerID)
        {
            CustomerViewModel model = new CustomerViewModel();
            if (CustomerID > 0)
            {
                model.CustomerID = 1;
                model.Name = "Jack Wilshere";
                model.Email = "Jack@gmail.com";
                model.City = "Arsenal";
            }
            return View(model);
        }
    
ViewModel:
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.ComponentModel.DataAnnotations;

        namespace HtmlHelpers.ViewModel
        {
            public class CustomerViewModel
            {
                public int CustomerID { get; set; }

                public string Name { get; set; }

                public string City { get; set; }

                public string Email { get; set; }
            }
        }
    
After the form is rendered on UI, we need to provide the CustomerID on the form and click on search button. The form is submitted to HTMLForm action method which accepts the CustomerID parameter. The value entered in the CustomerID field is present in the CustomerID parameter. You need to make sure that the ViewModel property name and the parameter name matches in order to receive the user input.

UI:

We will enter the CustomerID and will click on Submit button. The form is submitted to Action method with the entered CustomerID. We can use the parameter to fetch desired data from database. The data is displayed on UI as shown below.



There is another overload of this helper which accepts the htmlAttributes.

Overload with htmlAttributes:

    @using (Html.BeginForm("HtmlForm", "Home", FormMethod.Get, new { target = "_blank" }))
    {
        @Html.EditorForModel("CustomerViewModel")
        <input type="submit" id="SubmitButton" value="Submit" />
    }
    

In the above code, you are passing an anonymously typed object to the htmlAttribute parameter of BeginForm. You will also find an htmlAttributes parameter of type IDictionary<string, object> in a different overload. 
              In the above example, we have set target="_blank" using the htmlAttributes. We can set as many attribute values using the htmlAttributes parameter as necessary.

Inside BeginForm:


The BeginForm helper asks the routing engine how to reach the HtmlForm action of HomeController. Behind the scenes it uses the method name GetVirtualPath on the Routes property exposed by RouteTable.

No comments:

Post a Comment