tags:

views:

266

answers:

1

I am setting my header tag from the controller:

ViewData["H1"] = "Home > " + category + " > " + subcategory;

I would like Home and category to be urls, what is the best way to go about doing that?

+3  A: 

You should not do this. Your question is asking how to create HTML from the controller. Controllers should not create HTML. That's what a view is for. Instead, pass the category and subcategory to the view, and generate the HTML there:

    public ActionResult Foo()
    {
        ViewData["category"] = "Foo";
        ViewData["subcategory"] = "Bar";
        return View();
    }

<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
    <h3>Home &gt; <%=Html.ActionLink(ViewData["category"]) %>  
             &gt; <%=Html.ActionLink(ViewData["subcategory"]) %></h3>

Of course, do feel free to use a strongly typed model instead of the ViewData dictionary, but this should give you a general idea.

Note: my original answer follows. The question originally posed (see back revisions) was completely different than the question as it now stands. I'm leaving the original answer, because I think there is some value in it.

Before I get the answer, I'd be remiss if I didn't say that this example is wrong in a couple of different ways.

  1. Whether you should use code behind it all in an MVC app is, at the very least, debatable.
  2. You certainly should not be setting ViewData in a view. ViewData should be set in the controller and read in a view.

Now, with that said, the way to call Html.ActionLink in a code behind page is to, um, just call it. It works just fine, and return a string, just like it does in the aspx.

However, that's not what I'd recommend doing. Instead, make a helper for your header:

  1. Create a new, static class. Call it ViewHelpers or something.
  2. Add the namespace for this class to the pages->namespaces section in web.config
  3. Add a new method, Header (or whatever name you prefer) to the class. See the example below.
  4. Now called the helper from your view. Again, see the example below.

Examples:

public static class ViewHelpers
{
    public static string Header(this HtmlHelper helper, 
        string category, string subcategory)
    {
        return string.Format("Home > {0} > {1}",
           helper.ActionLink(category),
           helper.ActionLink(subcategory);
    }
}

<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
    <%= Html.Header("foo", "bar") %>

<pages [...]>
  [...]
  <namespaces>
    [...]
    <add namespace="Your.Namespace.ContainingYourClass"/>
  </namespaces>
</pages>
Craig Stuntz
Sorry, I meant controller!
KevinUK
No, you can't call ActionLink from a Controller. If you tell me what problem you're trying to solve, perhaps I could suggest a way to do it.
Craig Stuntz
Ah. I see you've now updated the question to a completely different question. I'll take a stab at that.
Craig Stuntz