1

So I have this class:

public class Link {
     public string Title { get; set; }
     public string Url { get; set:}
     public string Description { get; set; }
}

And I need to pass this to the view (A page of links), such that each Link.Title will appear as the clickable link text with Link.Url as the URL.

How exactly do I pass the model properties into a clickable link?

1 Answer 1

1

You can pass a collection of Link object to your view.

public ActionResult Index()
{
  var links = new List<Link>{
    new Link { Title="StackOverFlow", Url="http://www.stackoverflow.com", 
                                                                      Description="SO"},
    new Link { Title="SuperUser", Url="http://www.superuser.com",
                                                                      Description="SU"}
  };
  return View(links);
}

and your view, which is strongly typed to a collection of Link objects, simply loop through them and build the markup you want.

@IEnumerable<Link>
@foreach(var link in Model)
{
   <a href="@link.Url" title="@link.Description">@link.Title</a>
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the help, but why the "title = "@link.Description""? why not <a href="@link.Url">@link.Title</a>?
I thought you use the Description property for your title attribute(the small tool tip when you hover over). If you do not want it, just remove it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.