How to set a truly global variable in ASP.NET MVC 4? -
i building site pull images separate domain. domain doesn't exist yet, nor has name been concluded upon, time being need access images local directory. avoid manually changing every single image tag later on, i want use global variable can change once , affect every single image tag on website.
i have found 1 solution far, set key/value pair in web.config's appsettings so...
<appsettings> <add key="imagesource" value="/some/local/directory" /> </appsettings> then, in each view, @ top, add...
@{ string imgsrc = system.configuration.configurationmanager.appsettings["imagesource"]; } and in html use...
<img src="@imgsrc/my_image.jpg" alt="my image" /> this works still requires me assign variable in every single view template create. in spirit of dry, looking way can assign variable once , have presence implicit in every page, regardless of model, controller, or view.
i using extension methods on built-in htmlhelper class type of thing. can have htmlhelper extension such as:
public static mvchtmlstring imagereference( htmlhelper html, string id, string alttext, string imagenameandextension) { var baseurl = [go setting value]; string src = string.concat(baseurl, imagenameandextension); var img = new tagbuilder("img"); if (string.isnullorempty(id) == false) img.mergeattribute("id", id); if (string.isnullorempty(alttext) == false) img.mergeattribute("alt", alttext); img.mergeattribute("src", src); return mvchtmlstring.create(img.tostring(tagrendermode.selfclosing)); } then consume like:
@html.imagereference("theimage", "a cool image", "doublerainbow.png") usually end few overrides flowing through single method (e.g. no id parameter, etc.) there nice side-effects, too. if whole team uses these, end standardized markup.
more info: http://www.asp.net/mvc/tutorials/older-versions/views/creating-custom-html-helpers-cs
Comments
Post a Comment