简体   繁体   English

将 @Url.Action 存储在变量中

[英]store @Url.Action inside a variable

I am working on an ASP.NET MVC4 project.我正在开发一个 ASP.NET MVC4 项目。

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.在我的一个视图中,我试图将@Url.Action结果存储在字符串变量中,并将其传递到<a href="..."></a>链接中。

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'当我有if...else块出现在下面的代码片段中时,对actionHelper的第二次分配会抛出以下消息: Argument 3: cannot convert from '<anonymous type: int i, int page>' to 'System.Web.Routing.RouteValueDictionary'<a href="@actionHelper">操作引发以下错误: 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.但是当我注释掉else块中的赋值时,错误从 VS 错误窗口中消失了。 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> ?发生了一些奇怪的事情,所以与其关注上面的错误,我@Url.Action找出:有没有办法将@Url.Action存储在变量中并将其传递给<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:从对Url.Action方法的调用中删除@符号:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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