ASP MVC setup to define image folder
I'm new to asp mvc and would like to define links in views to images / content folder in such a way that I don't have to change every link if the images folder changes.
Is it possible to use ActionLink and routing, pooling or is there a better way to achieve this.
I couldn't find a good example anywhere, so I haven't tried anything coding far.
I'm going to store a fixed path somewhere, but is this really an mvc type solution?
source to share
There are several ways to do this. Here's one approach to extending the method Url.Content()
.
1. Creating an extension method
We will call 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 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 directory of your directory
<namespaces>
<add namespace="TestApp.Extensions"/>
</namespaces>
4. Use a new method
@Url.Virtual("{images}/mypic.png")
Output:
/Content/images/mypic.png
Now you can use Virtual()
wherever you would like Content()
.
This decision may be over the top, but it is all-encompassing.
source to share