使用AJAX MVC创建规范URL

时间:2014-05-09 12:01:04

标签: jquery asp.net-mvc url-rewriting

我有这样的网址 -

Home/Index/?Id=234&videotitle=testtitle

我想将此网址转换为规范网址,类似这样的内容 -

Home/Index/234/testtitle

方案 -

 @for (int i = 0; i < Model.Count(); i++)
        {

    <a href="javascript:;" id="video-@Model[i].vd_Id">@Model[i].videoname</a>


    $(function () {
            $('#video-@Model[i].vd_Id').click(function () {

                $.ajax({
                    url: '/Home/VideoInfo/?vd_Id=@Model[i].vd_Id' + '&videoview=' + '@Model[i].Video_view',
                    type: 'post',
                    success: function (data) {
                        window.location.href = "/Home/Video/ +'" + data.idofthisvideo + "'" + "/" + data.titleofthisvideo
                    }
                });
            });

        });

    </script>

}

当我点击锚点时,它会转到方法 -

  public JsonResult VideoInfo(long? vd_Id, long? videoview)
        {
            var dataa = (from u in db.Channels
                         select new Addvideo
                        {
                            videoname = dataa.videoname,
                            title = dataa.title,
                            vd_Id = Convert.ToInt64(dataa.vd_Id)
                        }).SingleOrDefault();

            var idofvideo = list.vd_Id;
            var titleofvideo = list.title;
            return Json(new { success = true, viewdata = list, idofthisvideo = idofvideo, titleofthisvideo = titleofvideo });

        }

注意

我通过Json结果收回Id和title,然后尝试以方式更改url -

success: function (data) {
                            window.location.href = "/Home/Video/ +'" + data.idofthisvideo + "'" + "/" + data.titleofthisvideo
                        }

这就是另一种方法 -

 public ActionResult Video(long? vd_Id)
          {
            .
            .
            .
            .
            .
          return view(someview); 

           }

然后它因服务器错误而失败并且这个网址 -

/Home/Video/%20+'234'/Test%20title

HTTP Error 404.11 - Not Found
The request filtering module is configured to deny a request that contains a double escape sequence.

如何将此网址转换为正确的规范网址?

1 个答案:

答案 0 :(得分:0)

在asp.net mvc 4项目的 App_Start 目录中的Url路由(RouteConfig类)中,添加如下操作:

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