【问题标题】:MVC broken image pathMVC损坏的图像路径
【发布时间】:2013-12-26 13:29:30
【问题描述】:

我在我的 MVC 应用程序中使用 jQuery DatePicker 插件。要为日历弹出窗口显示某个图像,我使用以下几行

 $.datepicker.setDefaults({
    showOn: "both",
    buttonImage: "../images/Calendar.png",
    buttonImageOnly: true,
    buttonText: "show calendar"
});

在我的观点中,我总是这样定义我的表单:

 @using (Html.BeginForm("Insert", "MyController", FormMethod.Post, new { id = "insertForm", onsubmit = "return confirm('Do you confirm insert operation?')" }))

当我在没有任何参数的情况下运行某个页面时,例如

http://localhost:52849/MyController/Insert

一切正常,日历图像显示正确。此外,当我使用 Firebug 检查元素时,我看到以下声明:

<img class="ui-datepicker-trigger" src="../images/Calendar.png" alt="Show Calendar" title="Show Calendar"/>

如果我在 Chrome 中复制图片 URL,我会得到 ​​p>

http://localhost:52849/images/Calendar.png

但是当我调用带有参数的页面时

http://localhost:52849/MyController/Insert/6

图像消失。当我用萤火虫检查按钮时,我仍然看到与

相同的声明
<img class="ui-datepicker-trigger" src="../images/Calendar.png" alt="Show Calendar" title="Show Calendar"/>

但是当我使用 Chrome 获取图片网址时,我得到了

http://localhost:52849/MyController/images/Calendar.png

它背后的原因是什么?如果不使用查询字符串或会话变量传递参数,我怎么可能解决这个问题

【问题讨论】:

    标签: jquery css asp.net-mvc image src


    【解决方案1】:

    发生这种情况是因为您使用的是 buttonImage 属性的相对路径。

    改为使用绝对路径,问题就解决了。

    例如:

     $.datepicker.setDefaults({
        showOn: "both",
        buttonImage: "/myapplication/images/Calendar.png",
        buttonImageOnly: true,
        buttonText: "show calendar"
    });
    

    (实际上,我通常定义一个包含应用程序根目录的 javascript 变量,然后将其与资源路径结合起来:这样,如果应用程序必须部署到不同的路径,则所有图像都不会休息。)

    例如:

     var appRoot = '<%=Request.ApplicationPath%>';
     $.datepicker.setDefaults({
        showOn: "both",
        buttonImage: appRoot + "/images/Calendar.png",
        buttonImageOnly: true,
        buttonText: "show calendar"
    });
    

    【讨论】:

    • 替换 var appRoot = location.protocol + "//" + location.host;解决了我的问题。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2012-08-15
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多