【问题标题】:how to using dynamic route on @Url.Action如何在@Url.Action 上使用动态路由
【发布时间】:2015-04-29 17:40:44
【问题描述】:

我尝试在 asp.net mvc 视图上创建动态链接,并使用来自数据库的值。 这是我的代码

@foreach (var menu in Model)
    {
        <li>
            <h4><span class="@menu.Glyphicon"></span> @menu.CategoryName</h4>
            <ul>
                @foreach (var mn in menu.LeftMenus)
                {
                    if (mn.RouteValue == null)
                    {
                        <li><a href="@Url.Action(@mn.ActionName, @mn.ControllerName)"><span class="glyphicon glyphicon-tasks"></span> @mn.MenuName</a></li>
                    }
                    else
                    {
                        <li><a href="@Url.Action(@mn.ActionName, @mn.ControllerName, new { @mn.RouteValue })"><span class="glyphicon glyphicon-tasks"></span> @mn.MenuName</a></li>
                    }
                }
            </ul>
        </li>
    }

当我将@RouteValue 解析为@url.Action 时,路由值是错误的,就像

<a href="/Import?RouteValue=workType%20%3D%201">

这是我的模特

public class LeftMenuViewModel
{
    public string CategoryName { get; set; }
    public string Glyphicon { get; set; }
    public List<LeftMenu> LeftMenus { get; set; }
}

public class LeftMenu
{
    public string MenuName { get; set; }
    public string ActionName { get; set; }
    public string ControllerName { get; set; }
    public object RouteValue { get; set; }
}

如何使用动态路由值?

【问题讨论】:

  • 你期望的 routevalue 是多少?
  • 你可以使用@Html.Encode(mn.RouteValue)
  • 我的目标是像这样创建 url.action
  • 试试&lt;a href="@Url.Action(mn.ActionName, mn.ControllerName, new { workType = Html.Encode(mn.RouteValue) })"&gt;&lt;/a&gt;
  • 问题是,我从数据库中获取工作类型,所以数据库中的值就像 workType = 1

标签: asp.net asp.net-mvc asp.net-mvc-3 razor


【解决方案1】:

我已经为我的问题找到了合适的答案。

这是我的模特

public class LeftMenuViewModel
{
    public string CategoryName { get; set; }
    public string Glyphicon { get; set; }
    public List<LeftMenu> LeftMenus { get; set; }
}

public class LeftMenu
{
    public string MenuName { get; set; }
    public string ActionName { get; set; }
    public string ControllerName { get; set; }
    public string ParameterName { get; set; }
    public object RouteValue { get; set; }
}

...在此之后,在我看来,我写这个:

RouteValueDictionary routeValue = new RouteValueDictionary();
                        routeValue.Add(@mn.ParameterName,@mn.RouteValue);
<li><a href="@Url.Action(@mn.ActionName, @mn.ControllerName, routeValue)"<span class="glyphicon glyphicon-tasks"></span> @mn.MenuName</a></li>

【讨论】:

    【解决方案2】:

    尝试使用类似路由值的参数名称设置

    new { @m.ParameterName = @mn.routeValue }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 2014-03-14
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      相关资源
      最近更新 更多