asp.net-mvc - ASP MVC 设置定义图像文件夹

标签 asp.net-mvc asp.net-mvc-4

我是 asp mvc 的新手,希望在 View 中定义图像/内容文件夹的链接,这样如果图像文件夹发生更改,我就不必更改每个链接。

可以使用 ActionLink 和路由、捆绑,或者有更好的方法来实现这一点。

我在任何地方都找不到一个好的例子,所以我没有尝试任何编码。

我正在考虑在某处存储固定路径,但这真的是 mvc 类型的解决方案吗?

最佳答案

有多种方法可以做到这一点。这是扩展 Url.Content() 方法的一种方法。

1。创建扩展方法

我们将其称为Virtual()

namespace TestApp.Extensions
{
    public static class UrlHelperExtensions
    {
        private const string _settingPattern = "path:{0}";
        private const string _regexPattern = @"\{\w+\}";

        public static string Virtual(this UrlHelper helper, string url)
        {
            Regex r = new Regex(_regexPattern);
            var matches = r.Matches(url);

            if (matches.Count == 0) return url;

            var sb = new StringBuilder(url);
            var keys = WebConfigurationManager.AppSettings.AllKeys;

            foreach (var match in matches)
            {
                string key = match.ToString().TrimStart('{').TrimEnd('}');
                string pattern = string.Format(_settingPattern, key);

                foreach (var k in keys)
                {
                    if (k == pattern)
                    {
                        sb.Replace(match.ToString(), WebConfigurationManager.AppSettings.Get(k));
                    }
                }
            }

            return helper.Content(sb.ToString());
        }
    }
}

2。将设置添加到主 Web.config

自由添加您想要的任何路径。

<add key="path:images" value="~/Content/images" />
<add key="path:scripts" value="~/scripts" />

3。将命名空间添加到 View 目录的 Web.config

<namespaces>
    <add namespace="TestApp.Extensions"/>
</namespaces>

4。使用新方法

@Url.Virtual("{images}/mypic.png")

输出:

/Content/images/mypic.png

您现在可以在 Content() 处使用 Virtual()

这个解决方案可以说有些过分,但它很全面。

关于asp.net-mvc - ASP MVC 设置定义图像文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25175920/

相关文章:

asp.net-mvc-4 - 使用包含而不是stringStartsWith knockout js

asp.net - 在处理请求之前找出 Controller 的名称和操作

asp.net - RenderBody() 和 RenderSection() 必须在每个子布局上?

javascript - 自定义 Javascript 在初始页面加载时未加载到 mvc 4 View 中

asp.net-mvc - 为什么应用程序池会自动停止?

asp.net-mvc - ASP.NET MVC Core 3.1 应用程序中的 CSHTML 更改、JS 更改所需的构建

c# - MVC5/C# : Pass LINQ inner Join query to view model

asp.net-mvc - 如何在.NET Web应用程序中创建用户身份验证?

asp.net-mvc - DbContext 已被释放并且 autofac

javascript - 如何将日期时间值附加到表单数据并在 Controller 中接收它