Monday, April 20, 2015

HTML Helpers - HyperLink example

We will take an example of HTML Helpers click here to learn more about HTML Helpers in ASP.Net MVC
We want to display all the customer in a bulletted list as shown below. Notice that all the customer names are rendered as hyperlinks.





When the hyperlink is clicked, the user will be redirected to customer details page, displaying the full details of the customer as shown below.



Copy and paste the following Index() action method in Customer Controller class. This method retrieves the list of employees, which is then passed on to the view for rendering.
public ActionResult Index()
{
    Customer Context customerContext = new CustomerContext();
    List<Customer > customer = customerContext.Customers.ToList();

    return View(customer);
}

At the moment, we don't have a view that can display the list of employees. To add the view
1. Right click on the Index() action method
2. Set
View name = Index
View engine = Razor
Select, Create a stronlgy-typed view checkbox
Select "Customer " from "Model class" dropdownlist
3. Click Add

At this point, "Index.cshtml" view should be generated. Copy and paste the following code in "Index.cshtml".
@model IEnumerable<MVCDemo.Models.Customer>

@using MVCDemo.Models;

<div style="font-family:Arial">
@{
    ViewBag.Title = "Customer List";
}

<h2>Customer List</h2>
<ul>
@foreach (Customer customer in @Model)
{
    <li>@Html.ActionLink(customer.Name, "Details", new { id = customer.Customer Id })</li>
}
</ul>
</div>

Points to Remember:
1. @model is set to IEnumerable<MVCDemo.Models.Customer>
2. We are using Html.ActionLink html helper to generate links

Copy and paste the following code in Details.cshtml
@Html.ActionLink("Back to List", "Index")

No comments:

Post a Comment