简体   繁体   中英

store @Url.Action inside a variable

I am working on an ASP.NET MVC4 project.

Within one of my views, I am trying to store an @Url.Action result inside a string variable, and pass it into an <a href="..."></a> link.

I am getting some weird results:

  • When I have the if...else block as it appears in my code snippet below, the 2nd assignment to actionHelper throws the following message: Argument 3: cannot convert from '<anonymous type: int i, int page>' to 'System.Web.Routing.RouteValueDictionary' and the <a href="@actionHelper"> operation throws the following error: Argument 4: cannot convert from 'object' to 'string'
  • But when I comment out the assignment in the else block, the error disappears from the VS error window. However, when I reload the page, I get a compilation error that states it is looking for an additional }

There is some weird stuff going on, so rather than focusing on the errors above, I am trying to find out: is there a way to store a @Url.Action inside a variable and pass it into an <a href="..."></a> ?

The code in my view is below:

@{
    string actionHelper = null;
}

    @if (resultEnd == Model.Search.CountSubjectItems && Model.Search.Page > 1)
    {
        if (!Model.Search.GeneralSearch)
        {
            actionHelper = @Url.Action("LandingPage", "Explore", new { i = Model.ID, page = Model.Page - 1 }, null);
        }
        else
        {
            actionHelper = @Url.Action("SearchPage", "Explore", new { i = Model.ID, page = Model.Page - 1 }, null);
        }
        <span>
            <a href="@actionHelper">
                <span class="glyphicon glyphicon-chevron-left" aria-hidden="true" title="Previous"></span> Prev
            </a>
        </span>
    }

Remove the @ sign from the calls to the Url.Action method:

if (!Model.Search.GeneralSearch)
{
    actionHelper = Url.Action("LandingPage", "Explore", new { i = Model.ID, page = Model.Page - 1 }, null);
}
else
{
    actionHelper = Url.Action("SearchPage", "Explore", new { i = Model.ID, page = Model.Page - 1 }, null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM