In ASP.Net web forms, developers are using the toolbox for adding controls on any particular page, in ASP.NET MVC application there’s no tool chest accessible to tug and drop markup language controls on the view. In ASP.NET MVC application, if you wish to make a view it ought to contain markup language code. So those developers who are new to MVC especially with web forms background finds this a little hard.

To overcome this downside, ASP.NET MVC provides HtmlHelper category that contains completely different strategies that assist you produce markup language controls programmatically. All HtmlHelper strategies generate markup language and come the result as a string. the ultimate markup language is generated at runtime by these functions. The HtmlHelper category is meant to get UI and it mustn’t be employed in controllers or models.

There are many different types of helper methods.

Createinputs − Creates inputs for text boxes and buttons.

Createlinks −Creates links that are based on information from the routing tables.

Createforms − Create form tags that can post back to our action, or to post back to an action on a different controller.

Given below is that the list of strategies in HtmlHelper category.
If you cross-check the view from the last chapter that we’ve generated from UserController index action, you’ll see the quantity of operations that started with markup language, like Html.ActionLink and markup language.DisplayNameFor, etc. as shown within the following code.

@model IEnumerable<MVCHelperDemo.Models.User>
@{
   Layout = null;
} 

<!DOCTYPE html>
<html>
   <head>
      <meta name = "viewport" content = "width = device-width" />
      <title>Index</title>
   </head>
	
   <body>
      <p>
         @Html.ActionLink("Create New", "Create")
      </p>
		
      <table class = "table">
         <tr>
            <th>
               @Html.DisplayNameFor(model => model.Name)
            </th>
				
            <th>
               @Html.DisplayNameFor(model => model.DateofBirth)
            </th>
				
            <th>
               @Html.DisplayNameFor(model => model.Age)
            </th>
				
            <th></th>
         </tr>
			
         @foreach (var item in Model) {
            <tr>
               <td>
                  @Html.DisplayFor(modelItem => item.Name)
               </td>
					
               <td>
                  @Html.DisplayFor(modelItem => item.DateofBirth)
               </td>
					
               <td>
                  @Html.DisplayFor(modelItem => item.Age)
               </td>
					
               <td>
                  @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                  @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                  @Html.ActionLink("Delete", "Delete", new { id = item.ID })
               </td>
            </tr>
         }
			
      </table>
   </body>
</html>

This markup language could be a property that we have a tendency to inherit from the ViewPage base category. So, it’s accessible altogether of our views associate degreed it returns an instance of a sort known as markup language Helper.

Let’s take a glance at a straightforward example during which we’ll modify the user to edit the worker. Hence, this edit action are going to be mistreatment important numbers of various markup language Helpers.

If you cross-check the higher than code, you’ll see at the top the subsequent markup language Helper strategies

@Html.ActionLink("Edit", "Edit", new )

In the ActionLink helper, the primary parameter is of the link that is “Edit”, the second parameter is that the action technique within the Controller, that is additionally “Edit”, and also the third parameter ID is of any specific worker you wish to edit.

Let’s amendment the UserController category by adding a static list and conjointly amendment the index action mistreatment the subsequent code.

public static List<User> userList = new List<User>{
   new User{
      ID = 1,
      Name = "Pawan",
      DateofBirth = DateTime.Parse(DateTime.Today.ToString()),
      Age = 23
   },
	
   new User{
      ID = 2,
      Name = "Rajesh",
      DateofBirth = DateTime.Parse(DateTime.Today.ToString()),
      Age = 45
   },
	
   new User{
      ID = 3,
      Name = "Diwakar",
      DateofBirth = DateTime.Parse(DateTime.Today.ToString()),
      Age = 37
   },
	
   new User{
      ID = 4,
      Name = "Rohit",
      DateofBirth = DateTime.Parse(DateTime.Today.ToString()),
      Age = 26
   },
	
};

public ActionResult Index(){
   var users = from e in userList
   orderby e.ID
   select e;
   return View(users);
}

Let’s update the Edit action. you’ll see 2 Edit actions one for GET and one for POST. Let’s update the Edit action for Get, that has solely Id within the parameter as shown within the following code.

// GET: User/Edit/5
public ActionResult Edit(int id){
   List<User> userList = GetUserList();
   var User= userList.Single(m => m.ID == id);
   return View(user);
}

Now, we all know that we’ve action for Edit however we have a tendency to don’t have any view for these actions. thus we’d like to feature a hold well. To do this, right-click on the Edit action and choose Add view.

Right-click Edit Action
You will see the default name for view. choose Edit from the example dropdown and worker from the Model category dropdown.

Following is that the default implementation within the Edit view.

@model MVCHelperDemo.Models.User
@{
   Layout = null;
}

<!DOCTYPE html>
<html>
   <head>
      <meta name = "viewport" content = "width = device-width" />
      <title>Edit</title>
   </head>
	
   <body>
      @using (Html.BeginForm()){
         @Html.AntiForgeryToken()
         <div class = "form-horizontal">
            <h4>User</h4>
            <hr />
            @Html.ValidationSummary(
               true, "", new { @class = "text-danger" })
					
            @Html.HiddenFor(model => model.ID)
				
            <div class = "form-group">
               @Html.LabelFor(
                  model => model.Name, htmlAttributes: new{
                     @class = "control-label col-md-2" })
							
               <div class = "col-md-10">
                  @Html.EditorFor(model => model.Name, new{
                     htmlAttributes = new {
                        @class = "form-control" } })
								
                  @Html.ValidationMessageFor(model => model.Name, "", new{
                        @class = "text-danger" })
               </div>
					
            </div>
				
            <div class = "form-group">
               @Html.LabelFor(
                  model => model.DateofBirth, htmlAttributes: new{
                     @class = "control-label col-md-2" })
							
               <div class = "col-md-10">
                  @Html.EditorFor(
                     model => model.DateofBirth, new{
                        htmlAttributes = new{ @class = "form-control" } })
								
                  @Html.ValidationMessageFor(
                     model => model.DateofBirth, "", new{
                        @class = "text-danger" })
               </div>
					
            </div>
				
            <div class = "form-group">
               @Html.LabelFor(
                  model => model.Age, htmlAttributes: new{
                     @class = "control-label col-md-2" })
							
               <div class = "col-md-10">
                  @Html.EditorFor(
                     model => model.Age, new{
                        htmlAttributes = new{ @class = "form-control" } })
								
                  @Html.ValidationMessageFor(
                     model => model.Age, "", new{
                        @class = "text-danger" })
               </div>
					
            </div>
				
            <div class = "form-group">
               <div class = "col-md-offset-2 col-md-10">
                  <input type = "submit" value = "Save" class = "btn btn-default"/>
               </div>
            </div>
				
         </div>
      }
		
      <div>
         @Html.ActionLink("Back to List", "Index")
      </div>
		
   </body>
</html>

As you’ll be able to see that there several helper strategies used. So, here “HTML.BeginForm” writes a gap type Tag. It conjointly ensures that the tactic goes to be “Post”, once the user clicks on the “Save” button.

Html.BeginForm is extremely helpful, as a result of it allows you to vary the uniform resource locator, amendment the tactic, etc.

In the higher than code, you’ll see another markup language helper which is “@HTML.HiddenFor”, that emits the hidden field.

MVC Framework is wise enough to work out that this ID field is mentioned within the model category and therefore it must be prevented from obtaining emended, that’s why it’s marked as hidden.

The Html.LabelFor markup language Helper creates the labels on the screen. The Html.ValidationMessageFor helper displays correct error message if something is wrong entered whereas creating the amendment.

We conjointly have to be compelled to amendment the Edit action for POST as a result of once you update the worker then it’ll decision this action.

// POST: User/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection){
   try{
      var user= userList.Single(m => m.ID == id);
      if (TryUpdateModel(user)){
         //To Do:- database code
         return RedirectToAction("Index");
      }
      return View(user);
   }catch{
      return View();
   }
}

Let’s run this application and request for the subsequent uniform resource locator http://localhost:63004/user. you’ll receive the subsequent output.

Localhost worker
Click on the edit link on any specific worker, let’s say click on Allan edit link. you’ll see the subsequent view.

Click specific worker
Let’s amendment the age from twenty three to twenty nine and click on ‘Save’ button, then you’ll see the updated age on the Index view.

One response on “Helpers in Asp.net MVC

  1. I have noticed that your page needs some fresh articles.

    Writing manually takes a lot of time, but there is tool
    for this boring task, search for: Wrastain’s tools for content

Leave a Reply

Your email address will not be published. Required fields are marked *