Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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:</p> <pre><code> public ActionResult Foo() { ViewData["category"] = "Foo"; ViewData["subcategory"] = "Bar"; return View(); } &lt;asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server"&gt; &lt;h3&gt;Home &amp;gt; &lt;%=Html.ActionLink(ViewData["category"]) %&gt; &amp;gt; &lt;%=Html.ActionLink(ViewData["subcategory"]) %&gt;&lt;/h3&gt; </code></pre> <p>Of course, do feel free to use a strongly typed model instead of the ViewData dictionary, but this should give you a general idea.</p> <p><strong>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.</strong></p> <p>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.</p> <ol> <li>Whether you should use code behind it all in an MVC app is, at the very least, debatable.</li> <li>You certainly should not be setting ViewData in a view. ViewData should be set in the controller and <em>read</em> in a view.</li> </ol> <p>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.</p> <p>However, that's not what I'd recommend doing. Instead, make a helper for your header:</p> <ol> <li>Create a new, static class. Call it ViewHelpers or something.</li> <li>Add the namespace for this class to the pages->namespaces section in web.config</li> <li>Add a new method, Header (or whatever name you prefer) to the class. See the example below.</li> <li>Now called the helper from your view. Again, see the example below.</li> </ol> <p>Examples:</p> <pre><code>public static class ViewHelpers { public static string Header(this HtmlHelper helper, string category, string subcategory) { return string.Format("Home &gt; {0} &gt; {1}", helper.ActionLink(category), helper.ActionLink(subcategory); } } &lt;asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server"&gt; &lt;%= Html.Header("foo", "bar") %&gt; &lt;pages [...]&gt; [...] &lt;namespaces&gt; [...] &lt;add namespace="Your.Namespace.ContainingYourClass"/&gt; &lt;/namespaces&gt; &lt;/pages&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload