Url.routeUrl返回null(我试过同样的问题)

时间:2016-06-23 12:04:03

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

大家好我想知道{Controller} / {action} / {postid} - {address} 但是routUrl返回null请帮我解决。(我是MVC中的新手)

我的路线配置是

routes.MapRoute(
            name: "Post",
            url: "Posts/Show/{postid}-{address}",
            defaults: new { controller = "Posts", action = "Index", postid = "", address = "" }
           );

和index.cshtml

<a href="@Url.RouteUrl("Post",new {item.PostId,item.Address })">@item.PostTitle</a>

生成的网址是 http://localhost:59066/Posts/Show/1-Post-with-Featured-Image

但在PostsController中

public ActionResult Show(string add)
    { return View();} 

“string add”为空!

3 个答案:

答案 0 :(得分:0)

我不会改变路线......

试试这个......

<a href="@Url.Action("Action","Controller",new {PostId = item.PostId, Address = item.Address })">@item.PostTitle</a>

这将发送PostId和Address作为参数,因此您可以在控制器中获取它们:

public ActionResult AwesomeThings(int PostId, String Address)
{
         var foo = PostId;
         var bar = Address;
        return View(model);
}

答案 1 :(得分:0)

路由没有变化,

Index.cshtml:

<a href="@Url.RouteUrl("Post",new {@postid = item.PostId, @address = item.Address },null)">@item.PostTitle</a>

控制器:

public ActionResult Show(string postid, string address)
{ return View();} 

答案 2 :(得分:0)

我将路线更改为

routes.MapRoute("Post", "post/{postid}-{address}", new { controller = "Posts", action = "Show" ,postid="",address=""}, namespaces);

并添加了一个具有相同控制器和操作的路径

routes.MapRoute("PostAddress", "post/{IdAndAdd}", new { controller = "Posts", action = "Show" }, namespaces);
routes.MapRoute("Post", "post/{postid}-{address}", new { controller = "Posts", action = "Show" ,postid="",address=""}, namespaces);

然后收到行动&#34; idAndAdd&#34;正确

public ActionResult Show(string idAndAdd)
    {
        var parts = SeperateAddress(idAndAdd);
        if (parts == null)
            return HttpNotFound();

        var post = db.Posts.Find(parts.Item1);
        if (post == null)
            return HttpNotFound();

        if (!post.Address.Equals(parts.Item2, StringComparison.CurrentCultureIgnoreCase))
            return RedirectToRoutePermanent("Post", new { postid = parts.Item1, address = post.Address });

        return View(post);
    }

    and it's worked .
相关问题