In ASP.NET WebForms you can reference appSettings directly in your markup with this syntax:
<%$ MySettingKey %>
Unfortunately this does not work in ASP.NET MVC because, as MSDN points out, this syntax on开发者_如何转开发ly works in server controls.
I've run into a few situations where I would love to use this syntactic sugar in an ASP.NET MVC view (WebFormsViewEngine). Does anyone know if there is a way to get this working?
Seems like we might be able to derive from WebFormsViewEngine and add this as a feature, perhaps?
Not very clean but in an ASP.NET MVC View you could actually write this:
<asp:Literal ID="dummy" runat="server" Text="<%$appSettings:MySettingKey%>" />
Which will effectively print whatever the value you have in appSettings:
<appSettings>
<add key="MySettingKey" value="SOME VALUE"/>
</appSettings>
Oh and there won't be a VIEWSTATE tag added to your page :-)
Now to the point: I will strongly discourage you doing something like this MVC. It is not the View's responsibility to pull the data to show, it's the controller that needs to pass it. So I would make MySetting a property of the ViewModel which will be populated by the controller and passed to the view to be shown.
public ActionResult Index()
{
var model = new SomeViewModel
{
// TODO: Might consider some repository here
MySetting = ConfigurationManager.AppSettings["MySetting"]
}
return View(model);
}
And in the View:
<%= Html.Encode(Model.MySetting) %>
or even shorter with the new syntax introduced in ASP.NET 4:
<%: Model.MySetting %>
UPDATE:
Yet another alternative if you think that MySetting is not a property of the ViewModel (like some css name or similar) you could extend the HtmlHelper:
public static string ConfigValue(this HtmlHelper htmlHelper, string key)
{
return ConfigurationManager.AppSettings[key];
}
And use it like this:
<%= Html.Encode(Html.ConfigValue("MySetting")) %>
In my memories, <%$ %> tag reference to globalzation resources, am I wrong?
It still works with server controls in MVC, so no one's stopping you from writing a simple control which will just print out the key.
I prefer to have something like an ApplicationFacade. This is something I picked up from Mark Dickinson when we worked together.
The premise is very similar to what Darin is proposing, except it is strongly typed...
public static class ApplicationFacade
{
public static string MySetting
{
get
{
return ConfigValue("MySetting");
}
}
//A bool!
public static bool IsWebsiteLive
{
get
{
return (bool)ConfigValue("IsWebsiteLive");
}
}
private static string ConfigValue(string key)
{
return ConfigurationManager.AppSettings[key];
}
}
Then you would call it in your view thus:
<%= ApplicationFacade.MySetting %>
精彩评论