Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ActionLInk from inside a helper template cshtml page

Why doesn't Html.ActionLink work in the below code? This is a page in the app_code folder, that I am trying to call from index.cshtml

LogOnUserControl.cshtml
@helper DisplayUserControl(){ if (Request.IsAuthenticated ) {

        <span>Welcome <strong>@User.Identity.Name</strong>!</span>
        <span>[ {@Html.ActionLink("","","")}  ]</span>

    }
    else {
        <span>[{@Html.ActionLink("","","") }]</span>

    }
    }

this is the line of code from index.cshtml. The call itself works, if I remove the Html.ActionLink statements the site loads fine. Is it that you can't use them in a nested page like this? How else can I generate dynamic links?

index.cshtml
@LogOnUserControl.DisplayUserControl()

like image 431
Doug Chamberlain Avatar asked May 31 '11 18:05

Doug Chamberlain


1 Answers

What's the idea with this action links? Why are you passing empty strings as arguments? I suppose you want to generate SignIn, SignOut links, don't you?

Also if you want to use HTML helpers inside shared helpers that you put in the App_Code folder you will need to pass them as arguments because they are not available:

@using System.Web.Mvc.Html

@helper DisplayUserControl(System.Web.Mvc.HtmlHelper html) {
    if (html.ViewContext.HttpContext.User.Identity.IsAuthenticated) {
        <span>
            Welcome 
            <strong>
                @html.ViewContext.HttpContext.User.Identity.Name
            </strong>
            !
        </span>
        <span>[@html.ActionLink("SignOut", "Login")]</span>
    }
    else {
        <span>[@html.ActionLink("SignIn", "Login")]</span>
    }
}

and to call the helper:

@LogOnUserControl.DisplayUserControl(Html)

Personally I never use such helpers (the ones you put in the App_Code folder). Can't see any use for them when you have partial views, editor/display templates and Html.Action helpers.

So for example you could define a partial (~/Views/Shared/_LogOnUserControl.cshtml):

@if (User.IsAuthenticated) {
    <span>
        Welcome 
        <strong>
            @User.Identity.Name
        </strong>
        !
    </span>
    <span>[@Html.ActionLink("SignOut", "Login")]</span>
}
else {
   <span>[@Html.ActionLink("SignIn", "Login")]</span>
}

which you would include in your layout:

@Html.Partial("_LogOnUserControl")
like image 100
Darin Dimitrov Avatar answered Oct 14 '22 07:10

Darin Dimitrov