What is the purpose of Html helpers in MVC?

In this article we will understand What is the purpose of Html helpers in MVC? and How to generate DropDownList using Html helpers in Asp.net MVC by Sagar Jaybhay.





Html helpers





What is an Html Helper?





Html helper is a method that is used to render HTML content in a view. Html helpers are implemented using an extension method.





If you want to create an input text box with id=email and name is email





<input type=text id=email name=email value=’’/>




This is all Html we need to write by using the helper method it becomes so easy





@Html.TextBox(‘email’)




It will generate textbox control whose name is email.





If we want to assign the value of the textbox with some initial value then use below method.





@Html.TextBox(‘email’,’sagar@gmail.com’)




If I want to set an initial style for textbox we can achieve this by using below way.





@Html.TextBox(‘email’,’sagar@gmail.com’,new style=’your style here’ , title=’your title here’);




Here style we pass is an anonymous type.





If we have reserved keyword like class readonly like that and we want to use this as an attribute how we will do this is doing below way means append with @ symbol with the reserved word.





@Html.TextBox(‘email’,’sagar@gmail.com’,new @class=’class name’, @readonly=true);




If we want to generate label





@Html.Label(‘firstname’,’sagar’)




For password use below Html helper method to create password box





@Html.Password(“password”)




If I want to generate textarea then for this also we have a method





@Html.TextArea(“comments”,”,4,12,null)




In above code 4 is the number of rows and 12 is the number of columns





To generate a hidden box





@Html.Hidden(“EmpID”)




Hidden textboxes are not displayed on the web page but used for storing data and when we need to pass data to action method then we can use that.





Is it possible to create our Html helpers in asp.net MVC?





No, we can use plain Html for that but Html helpers reduce a significant amount of Html code to write that view.





Also, your code is simple and maintainable and if you required some complicated logic to generate view then this is also possible.





How to generate DropDownList from database values in Asp.Net MVC?





DropDown List Using Html Helpers In MVC




To achieve the above functionality we need to Create one controller in our project so we created the DropDownListDemo controller in our application. By creating this Index method is created by default. In our Business class we GetDepartments method present so we call this method from our controller.





public ActionResult Index()


ViewBag.Departments =new SelectList(this.business.GetDepartments(), "DepartmentID", "DepartmentName");

return View();





See the above method in this we Create SelectList object and assign this ViewBag property. Focus on name of ViewBag property and what name given in our Html code is same. So by convention, it’s bind this property value directly to our DropDownList.





Below is code for Full Controller which we Created





public class DropDownListDemoController : Controller

private BusinessLogic.Business business = null;
public DropDownListDemoController()

this.business = new BusinessLogic.Business();


// GET: DropDownListDemo
public ActionResult Index()


ViewBag.Departments =new SelectList(this.business.GetDepartments(), "DepartmentID", "DepartmentName");

return View();






Below is code for Index.cshtml file





@
ViewBag.Title = "Index";




<h2>Department List From Database</h2>


@Html.DropDownList("Departments","Select Department")




Now in Business Class, we have GetDepartments method already present which is shown below





public List<Department> GetDepartments()

List<Department> departments = new List<Department>();
string query = "select * from Department order by DepartmentID";
var data = this.dataAccess.GetTable(query);
if(data!=null&&data.Rows.Count>0)


foreach(DataRow dataRow in data.Rows)

var dept = new Department()

DepartmentID = Convert.ToInt32(dataRow["DepartmentID"].ToString()),
DepartmentName = dataRow["DepartmentName"].ToString()
;
departments.Add(dept);



return departments;






If you want  to see data from our Database table which is shown below image





DropDownList from DataBase fields




To summarize all if we want to generate DropDownList we have Html.DropDownList Html helper method. In this DropDownList in MVC is a collection of SelectListItem objects.





Now we can Create DropDownList then how we set Item selected in that DropDownList when all options are loaded. If you see above code no department is loaded by default it only shows Select Department but we want Engineering Department loaded by default how we create this.





DropDown List Default Selected




To create this first we need to alter our department table and add one column isSelected or not. To alter our table use below code





alter table [Department]
add isSelected bit




Default Selection Of DropDown List





After this, we need to add the isSelected field in our department model so our department class will change like this





public class Department

public int DepartmentID get; set;
public string DepartmentName get; set;

public bool? isSelected get; set;





After this, we need to Set the Engineering Department by default selected so we set the value to 1 in the Engineering department for that below query is used.





 update [Department] set isSelected=1 where DepartmentID=2




Now we need to add method in our business class from which we will retrieve all the values like DepartmentID, DepartmentName, isSelected column.





public List<Department> GetDepartment()

List<Department> departments = new List<Department>();
string query = "select * from Department order by DepartmentID";
var data = this.dataAccess.GetTable(query);
if (data != null && data.Rows.Count > 0)


foreach (DataRow dataRow in data.Rows)

var dept = new Department()

DepartmentID = Convert.ToInt32(dataRow["DepartmentID"].ToString()),
DepartmentName = dataRow["DepartmentName"].ToString(),
isSelected = (dataRow["isSelected"] !=DBNull.Value ? Convert.ToBoolean(dataRow["isSelected"]) : false)

;
departments.Add(dept);



return departments;






Below is the method in our controller where we created a SelectListItem list and add data from our database table. In below we use bool to cast because we added Nullable field in DepartmentModel





public ActionResult DefaultSelectedDrop()

List<SelectListItem> selectLists = new List<SelectListItem>();
foreach(var items in this.business.GetDepartment())

var p = new SelectListItem()

Text=items.DepartmentName,
Value=items.DepartmentID.ToString(),
Selected=(bool)items.isSelected

;
selectLists.Add(p);


ViewBag.Departments = selectLists;
return View();





And our view code is shown below





@
ViewBag.Title = "DefaultSelectedDrop";


<h2>Default Selected DropDownList</h2>


@Html.DropDownList("Departments", "Select Department")




GitHub :- https://github.com/Sagar-Jaybhay/MVC5

Comments

Popular posts from this blog

How to Start a YouTube Channel Free - Complete Guide

How Angular know which module is the startup module?

How to Start a YouTube Channel Free - Complete Guide