hyperlink  in ASP.NET using Razor

maqskywalker
maqskywalker used Ask the Experts™
on
Hi experts,

I'm learning to work with hyperlinks in MVC views.
So I created the example below to illustrate my question.

I have a ASP.NET MVC 5 application. I'm using C# and Razor.

I have an example that uses database first model.
I'm using the Employees table from the Northwind sql server database.

My application directory looks like this.

p1.PNG
My model looks like this:

EntityModel.PNG
My controller looks like this:

HomeController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using NorthwindApp.Models;

namespace NorthwindApp.Controllers
{
    public class HomeController : Controller
    {
        // ASP.NET Scaffolding in Visual Studio 2013
        // http://www.asp.net/visual-studio/overview/2013/aspnet-scaffolding-overview
        // Getting Started with Entity Framework 6 Database First using MVC 5
        // http://www.asp.net/mvc/overview/getting-started/database-first-development/setting-up-database

        private NorthwindEntities db = new NorthwindEntities();

        //***************************** INDEX *****************************
        // GET: Home
        public ActionResult Index()
        {
            var employees = db.Employees.Include(e => e.Employee1);
            return View(employees.ToList());
        }
        //***************************** INDEX *****************************

        //***************************** DETAILS *****************************
        // GET: Home/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }
        //***************************** DETAILS *****************************
        //***************************** CREATE *****************************
        // GET: Home/Create
        public ActionResult Create()
        {
            ViewBag.ReportsTo = new SelectList(db.Employees, "EmployeeID", "LastName");
            return View();
        }

        // POST: Home/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "EmployeeID,LastName,FirstName,Title,TitleOfCourtesy,BirthDate,HireDate,Address,City,Region,PostalCode,Country,HomePhone")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ReportsTo = new SelectList(db.Employees, "EmployeeID", "LastName", employee.ReportsTo);
            return View(employee);
        }
        //***************************** CREATE *****************************
        //***************************** EDIT *****************************
        // GET: Home/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            ViewBag.ReportsTo = new SelectList(db.Employees, "EmployeeID", "LastName", employee.ReportsTo);
            return View(employee);
        }

        // POST: Home/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "EmployeeID,LastName,FirstName,Title,TitleOfCourtesy,BirthDate,HireDate,Address,City,Region,PostalCode,Country,HomePhone,Extension,Notes,ReportsTo,PhotoPath")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Entry(employee).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ReportsTo = new SelectList(db.Employees, "EmployeeID", "LastName", employee.ReportsTo);
            return View(employee);
        }
        //***************************** EDIT *****************************
        //***************************** DELETE *****************************
        // GET: Home/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: Home/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Employee employee = db.Employees.Find(id);
            db.Employees.Remove(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        //***************************** DELETE *****************************

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

Open in new window


My Index.cshtml page looks like this:

@*a LIST of items of your MODEL type*@
@*IEnumerable basically is a collection*@
@*You controller will pass a LIST of object into this view*@
@model IEnumerable<NorthwindApp.Models.Employee>

@{
    ViewBag.Title = "Northwind Employees";
}

<!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.LastName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.FirstName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Title)
            </th>
            <th></th>
        </tr>
    
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.EmployeeID }) |
                @Html.ActionLink("Details", "Details", new { id=item.EmployeeID }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.EmployeeID })
            </td>
        </tr>
    }

    </table>
</body>
</html>

Open in new window



When I run my app, the Index.cshtml looks like this:

p2.PNG

How do I add a hyperlink column to my table that will take the users to http://www.google.com and add the item.EmployeeID to the end of the url

I tried to add it like this. But that didn't work.

                @* link label - name of view - append value to end of link *@
                @Html.ActionLink("External Link", "http://www.google.com/", new { id = item.EmployeeID })

When I run my page with this view:

@*a LIST of items of your MODEL type*@
@*IEnumerable basically is a collection*@
@*You controller will pass a LIST of object into this view*@
@model IEnumerable<NorthwindApp.Models.Employee>

@{
    ViewBag.Title = "Northwind Employees";
}

<!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.LastName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.FirstName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Title)
            </th>
            <th></th>
        </tr>
    
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @* link label - name of view - append value to end of link *@
                @Html.ActionLink("Edit", "Edit", new { id=item.EmployeeID }) |
                @Html.ActionLink("Details", "Details", new { id=item.EmployeeID }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.EmployeeID })
            </td>
            <td>
                @* link label - name of view - append value to end of link *@
                @Html.ActionLink("External Link", "http://www.google.com/", new { id = item.EmployeeID })
            </td>
        </tr>
    }

    </table>
</body>
</html>

Open in new window


It looks like this

p3.PNG
When I click on the External Link for the first record it goes here: http://localhost:6219/Home/http%3a/www.google.com/1
When I click on the External Link for the 2nd record it goes here: http://localhost:6219/Home/http%3a/www.google.com/2

I would like them to go here:
http://www.google.com/?employeeid=1
http://www.google.com/?employeeid=2

How do i fix my link?

Could I just use a regular html hyperlink tag like this?

<a id="ExternalHyperlink" href="http://www.google.com" target="_blank">External Link</a>
           
How would I add id=item.EmployeeID to the end of the href in this tag?
or
How would i add @Html.DisplayFor(modelItem => item.EmployeeID) to the end of the href in this tag?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Try something like this:
<td><a href="http://google.com/employeeid=@item.EmployeeID">Google</a></td>

Open in new window

Dirk StraussSenior Full Stack Developer
Distinguished Expert 2017
Commented:
Html.ActionLink is used for creating links to actions defined in MVC controllers which reside in the same app. So this is the reason you are seeing the localhost bit. Depending on your requirements, you can just link to the URL directly. There is no need to use Html.ActionLink, because you don't need any of the functionality it provides (in this case).

If the URL will always be linking to a specific URL, then just add this to your view. The EmployeeID will obviously change and would be the only variable part of this URL. If however, the URL needs to change based on the EmployeeID, then you will need to add these to your model as a collection and determine which URL is the correct one based on the EmployeeID you have.

From your example though, it seems like you will only always have a single external URL to link so. So just add it to the markup as a link and add your EmployeeID.

Author

Commented:
thanks

Author

Commented:
thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial