本文介绍了按下"MVC"后更改网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我要更改:

www.testurl.com/sports/blog/1

运动是我的专长,博客是我的行为,1是博客文章的ID,用于:

Where sports is my area, blog is my action and 1 is an ID of a blog post, to:

www.testurl.com/sports/blog/test-title-of-blog

仍然是我的博客,但未显示ID,而是博客的标题/永久链接.

Where blog is still my action but the id is not shown, but instead the title/permalink of the blog is.

这是我执行此操作的AreaRegistration:

Here is my AreaRegistration for this action:

context.MapRoute(
                "sports",
                "sports/{action}/{content}",
                new { area = "Sports", controller = "Sports", action = "", content = "" });

这是我目前的动作:

[HttpGet]
    public ActionResult Blog(string content)
    {
            int contentId;
            if (Int32.TryParse(content, out contentId))
            {
                model = service.GetBlogById(contentId);
            }
            else
            {
                model = service.GetBlogByTitle(content);
            }

            //Change URL to be: www.testurl.com/sports/blog/ + model.SEOFriendlyTitle
            return View(model);
    }

用户既可以通过博客的ID进行搜索,也可以通过博客的标题进行搜索,但我只希望标题显示在网址栏中,而不是ID.

Users are able to search via the ID of the blog, but also by the title of it, but I only want the title to appear in the url bar, never the id.

由于可能会导致持续的维护,因此我无法通过重定向规则执行此操作.

I cannot do this via Redirect rules due to the continuing maintenance that would cause.

  1. 控制器是执行此操作的正确位置吗?-请记住,直到使用ID从数据库中检索到标题后,我才可能没有标题

  1. Is the controller the right place to do this? -Remember I may not have my title until after I retrieve it from the database using the ID

如何更改URL以显示标题和ID?

推荐答案

我认为您应该做的是,如果ID为数字并且是有效的contentId,则将RedirectResult返回到新的网址:

I think what you should do is return a RedirectResult to the new Url if the ID is numeric and is a valid contentId :

            int contentId;
            if (Int32.TryParse(content, out contentId))
            {
                model = service.GetBlogById(contentId);
                if(model != null)
                {
                    return RedirectResult(/*url using the title*/);
                }
            }
            else
            {
                model = service.GetBlogByTitle(content);
            }

            //Change URL to be: www.testurl.com/sports/blog/ + model.SEOFriendlyTitle
            return View(model);

当然,这将导致服务器的另一次往返,但是我可以看到一种无需页面重定向即可更改浏览器URL的方法.您还应该确保您网站上所有发布的网址都使用标题而不是ID.

Of course, that will cause another round trip to the server but I can see a way to change the browser URL without a page redirect. You should also make sure that all published urls on your site are using the title instead of Id.

我希望它会有所帮助.

这篇关于按下"MVC"后更改网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 19:08