【问题标题】:jquery datepicker goto relative date urljquery datepicker goto 相对日期 url
【发布时间】:2011-12-22 05:11:48
【问题描述】:

我正在使用带有 jquery datepicker 小部件的 asp.net mvc3。我希望用户单击日期并转到该日期的网址。例如。 http://mysite.com/home/index/20111231

我找到了一个类似的帖子,但它不会指向相对网址。 jQuery UI Datepicker go to date URL

我的代码在第一次点击时有效,但在第二次点击时,网址翻了一番并给了我 404 错误。 第一次点击:http://mysite.com/home/index/20111231 第二次点击:http://mysite.com/home/index/home/index/20111231

查看代码:

<script type="text/javascript">
    $(document).ready(function () {
        $("#datepicker").datepicker({
            beforeShowDay: function (date) {
                return [true, "active"];
            },
            onSelect: function (dateText, inst) {
                document.location.href = "Home/Index/" + dateText;
            },
            onChangeMonthYear: function(year, month, inst)
            {
            },
            dateFormat: "yymd",
            showOtherMonths: true,
            selectOtherMonths: true,
            changeMonth: true
        });
    });
</script>
<h2>@ViewBag.Message</h2>
<div id="datepicker">
</div>

控制器中的代码:

public class HomeController : Controller
{
    public ActionResult About()
    {
        return View();
    }

    public ActionResult Index(string id)
    {
        ViewBag.Message = "Welcome " + id;

        return View();
    }
}

更新: 我的解决方案是在服务器上生成虚拟路径并将其粘贴到客户端html。

document.location.href = '@Request.Url.GetLeftPart(UriPartial.Authority)@HttpRuntime.AppDomainAppVirtualPath' + "/Home/Index/" + dateText;

【问题讨论】:

    标签: jquery asp.net-mvc-3 datepicker relative-path


    【解决方案1】:

    您需要在路径的开头添加/

    document.location.href = "/home/Index/" + dateText;

    【讨论】:

    • 我尝试将“/”添加到开头,但我还需要将虚拟目录名称硬编码到它。这不是一个好的解决方案。但你提醒我,我可以在服务器上获取虚拟目录并将其粘贴在客户端 html 上。请参阅更新的解决方案。
    【解决方案2】:

    我建议使用 URL 帮助程序来构建 URL。这种方式在您更改路线等后仍然有效。

    @Url.Action("Index", "Home", new { id = dateText })
    

    【讨论】:

    • 它几乎可以工作,但 dateText 是 javascript,而不是 c# 代码。所以我得到编译错误。
    • 啊,我可以强制 Url Helper 创建 rout url,然后在 javascript 中解析它。 var url = '@Url.Action("Index", "Home", new { id = 0 })'; url = url.substr(0, url.length - 1) + dateText; document.location.href = url;
    • 你是对的 - 如果它使用 JavaScript 构建会更棘手。我认为解析方法是一种适当的解决方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 2012-02-13
    • 2012-03-10
    • 2010-12-11
    • 2011-06-22
    相关资源
    最近更新 更多