如果查询字符串包含某些参数,如何在Razor视图中显示链接?

时间:2014-09-24 15:46:17

标签: html asp.net-mvc razor

当我转到ReportsController的索引视图时,有时我得到这样的链接:

http://localhost:17697/Reports

有时这样取决于我来自哪里:

http://localhost:17697/Reports?personId=15

我想显示此按钮:

 @Html.ActionLink("Back to person", "Person", new { id = PERSON_ID_FROM_QUERYSTRING }, new { @class = "btn btn-info btn-xs" })

如果?personId存在于链接中(是其一部分)。

怎么做?

4 个答案:

答案 0 :(得分:2)

可以在Request属性上访问URL参数。

因此,您可以检查此特定请求Request["personId"],如果不为null,请编写操作:

@{
    string pid = Request["personId"];
    if(!String.IsNullOrEmpty(pid)) {
        @Html.ActionLink("Back to person", "Person", new { id = pid }, new { @class = "btn btn-info btn-xs" });
    }
}

答案 1 :(得分:1)

也许您已经意识到这一点,并且只是试图避免在控制器中执行此操作,但为了完整性,我将包括在MVC中检索查询字符串参数的常见做法:

public class HomeController {

    public ActionResult Reports(int? personId) // this indicates optional query string param
    {
        vm = new ReportsViewModel{ PersonId = personId; };
        vm.Reports = Repository.GetReports();
        return View(vm);
    }
}

<强> CSHTML:

@if( Model.PersonId != null)
{
    Html.ActionLink("Back to person", "Person", new { id = Model.PersonId }, new { @class = "btn btn-info btn-xs" })
}

答案 2 :(得分:0)

假设PersonId是模型的一部分,您可以在视图中引用它:

@Html.ActionLink("Back to person", "Person", new { id = Model.PersonId }, 
                 new { @class = "btn btn-info btn-xs" })

答案 3 :(得分:0)

您可以像这样使用RouteData字典:

@Html.ActionLink("Back to person", "Person", new { id = ViewContext.RouteData.Values["personId"]}

对于更复杂的方案,请查看this post