【问题标题】:ViewData is not displaying information passed through URL MVC 5ViewData 不显示通过 URL MVC 5 传递的信息
【发布时间】:2015-10-23 06:56:01
【问题描述】:

我已经安装了 Visual Studio 2015 [我的 Win 7 上的免费一个],并且刚刚开始评估它的酷炫功能。 尝试使用这样的视图数据:

public class VandVController : Controller
{
    // GET: VandV
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult DisplayName(string name)
    {
        ViewData["name"] = name;
        return View();
    }
}

我的视图页面如下所示:

@{
ViewBag.Title = "DisplayName";
}

 <h2>Welcome to MVC training Mr. @ViewData["name"]</h2>

从我的网址,当我这样使用时:

 http://localhost:54748/VandV/DisplayName/abc

它向我展示:欢迎来到 MVC 培训先生。 它应该显示在哪里:欢迎来到 MVC 培训 abc 先生。

这是我的路线:

 public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

谁能告诉我怎么了?如何显示正确的刺痛?谢谢。

【问题讨论】:

  • 请显示您的路线,可能name 未填写
  • 你有.../{name}的具体路线吗?
  • 非常感谢。不错的收获。将我的路线从 id 更改为 name。

标签: .net asp.net-mvc asp.net-mvc-5 viewdata


【解决方案1】:

修改如下并正常工作。

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{name}",
        defaults: new { controller = "Home", action = "Index", name = UrlParameter.Optional }
    );
}

【讨论】:

    【解决方案2】:

    在您的配置中添加另一个路由路径(更改路由路径名称)并更改参数名称示例,如下所示

    routes.MapRoute(
                    "Test", // Route name
                    "{controller}/{action}/{name}", // URL with parameters
                    new { controller = "Home", action = "Index", name = UrlParameter.Optional } // Parameter defaults
                );
    

    【讨论】:

      【解决方案3】:
      public static void RegisterRoutes(RouteCollection routes)
      {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
          routes.MapRoute(
              name: "Default",
              url: "{controller}/{action}/{id}",
              defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
          );
      }
      

      使用新的

       {controller="VandV" ,action="DisplayName",id = UrlParameter.Optional} 
      

      【讨论】:

      • 这与问题有什么关系?这是因为参数需要是{name} 而不是{id}
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多