Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP MVC setting defining images folder

I am a newbie in asp mvc, and would like to define links in views to image/content folder in a way so I don't have to change each link if a image folder changes.

Is is possible using ActionLink and routing, bundling or there is a better way to achieve this.

I could not find a good example anywhere so I did not try anything any coding far.

I am thinking of storing a fixed path somewhere, but is that really a mvc type solution?

like image 793
mko Avatar asked Jun 07 '26 00:06

mko


1 Answers

There are a number of ways you could do this. Here's one approach to extend the Url.Content() method.

1. Create an extension method

We'll called it 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. Add settings to the main Web.config

Freely add any paths you want.

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

3. Add the namespace to the Web.config of your views directory

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

4. Use the new method

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

Output:

/Content/images/mypic.png

You can now use Virtual() where you would Content().

This solution is arguably excessive, but it is comprehensive.

like image 161
Rowan Freeman Avatar answered Jun 10 '26 18:06

Rowan Freeman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!