Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Thursday, November 6, 2014

Using the DropDownList Helper with ASP.NET MVC


This post will teach you the basics of working with the DropDownList helper helper in an ASP.NET MVC Web application.
The DropDownList helper used to create an HTML select list requires a IEnumerable , either explicitly or implicitly. That is, you can pass the IEnumerable explicitly to the DropDownList helper or you can add the IEnumerable to the ViewBag using the same name for the SelectListItem as the model property.
Let's suppose you want to show list of Animals as dropdownlist

public static List<String> GetPets()
        {
            List<string> petList = new List<string>();
            petList.Add("Dog");
            petList.Add("Cat");
            petList.Add("Hamster");
            petList.Add("Parrot");
            petList.Add("Gold fish");
            petList.Add("Mountain lion");
            petList.Add("Elephant");

            return petList;
        }

Open your controller method and add items to ViewBag item by passing the item to SelectList.

public ActionResult Index()
        {

            ViewData["Pets"] = new SelectList(GetPets());
            return View();
        }

In your view add following razor helper method.Run the application you will see that dropdownlist is generaeted

@Html.DropDownList("pets")

The above was very simple form.Let's create a complex form with some other information.In this example I am going to create a simple user registration form.Create two class named Country and Registration in model folder and add following code


public class Registration
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string County { get; set; }

    }
    public class Country
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

After that create a RegistrationViewModel class in Model folder and paste the following code

public class RegistrationViewModel
    {
        private readonly List<Country> _countries;
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string County { get; set; }

        public int SelectedCountryID { get; set; }
        public RegistrationViewModel()
        {
            List<Country> countries = new List<Country>(){
                new Country{Id=1,Name="India"},
                new Country{Id=2,Name="USA"},
                new Country{Id=3,Name="UK"},
                new Country{Id=4,Name="Australia"},
                new Country{Id=5,Name="Nepal"},
            };
            _countries = countries;
        }
        public IEnumerable<SelectListItem> Contry
        {
            get { return new SelectList(_countries, "Id", "Name"); }
        }
    }
The tricky part here is that I have added a readonly property Country that returns list of countries which I will pass to DropDownListFor helper function.Create two action methods in your controller as below.Right click on Create action method and generate strongly type view.Open the genrated view and modify the Country section as below

      <div class="editor-field">
            @Html.DropDownListFor(model => model.SelectedCountryID, Model.Contry)
            @Html.ValidationMessageFor(model => model.County)

        </div>


public ActionResult Create()
        {
            RegistrationViewModel model = new RegistrationViewModel();
            return View(model);
        }
        [HttpPost]
        public ActionResult Create(RegistrationViewModel _model)
        {
            RegistrationViewModel model = _model;
            return View(model);
        }


@model eManagerDemo.Models.RegistrationViewModel

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>RegistrationViewModel</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.County)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.SelectedCountryID, Model.Contry)
            @Html.ValidationMessageFor(model => model.County)

        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

If you run the application by pressing F5 you will see following output as shown in below image.


How to create html helper in razor (.NET MVC)


Razor is an ASP.NET programming syntax used to create dynamic web pages with the C# or Visual Basic .NET programming languages.The Razor syntax is a template markup syntax, based on the C# programming language, that enables the programmer to use an HTML construction workflow[clarification needed]. Instead of using the ASP.NET .ASPX markup syntax with <%= %> symbols to indicate code blocks, Razor syntax starts code blocks with a @ character and does not require explicit closing of the code-block.

HTML Helper
Html helper are much like asp.net control that return html string.But HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an event model and a view state.
In this post I will show you how to create Html helper in MVC.NET.There are two ways to create html helper in MVC.
Inline Helpers
These are create in the same view by using the Razor @helper tag. These helpers can be reused only on the same view.For example in following code snippet I have created a ToUpper html helper that wrap the text inside b tag and converts  the text to upper case 

@helper ToUpper(string text) { 
        
        @text.ToUpper()
    
    }
@{
    ViewBag.Title = "Demo";
    Layout = null;
}


@ToUpper(@ViewBag.Message)

Custom Helper
If you want to use your Html helper in application level then you can create custom helper.
You can create custom helper function by creating extensions method.In following code snippet I have created a SubmitButton html helper that generate submit button.



public static class HtmlHelpers
    {
        public static MvcHtmlString SubmitButton(this HtmlHelper helper, string text)
        {
            string str = "<input type=\"submit\" value=\"" + text + "\" />";
            return new MvcHtmlString(str);
        }
    }

How to use custom Helper

@Html.ToUpper("Submit")