Using <% $%> in ASP.NET MVC

In ASP.NET WebForms, you can reference appSettings directly in your markup using this syntax:

<%$ MySettingKey %>

Unfortunately, this does not work in ASP.NET MVC because, as MSDN points out, this syntax only works in server controls.

I came across several situations in which I would like to use this syntactic sugar in ASP.NET MVC view (WebFormsViewEngine). Does anyone know if there is a way to make this work?

It looks like we could extract from WebFormsViewEngine and add this as a function, maybe?

+3
source share
4 answers

, ASP.NET MVC View :

<asp:Literal ID="dummy" runat="server" Text="<%$appSettings:MySettingKey%>" />

, appSettings:

<appSettings>
    <add key="MySettingKey" value="SOME VALUE"/>
</appSettings>

, VIEWSTATE: -)

- MVC. View, , . MySetting ViewModel, .

public ActionResult Index()
{
    var model = new SomeViewModel
    {
        // TODO: Might consider some repository here
        MySetting = ConfigurationManager.AppSettings["MySetting"]
    }
    return View(model);
}

:

<%= Html.Encode(Model.MySetting) %>

ASP.NET 4:

<%: Model.MySetting %>

UPDATE:

, , MySetting ViewModel (, - css ), HtmlHelper:

public static string ConfigValue(this HtmlHelper htmlHelper, string key)
{
    return ConfigurationManager.AppSettings[key];
}

:

<%= Html.Encode(Html.ConfigValue("MySetting")) %>
+7

, <% $% > , ?

0

It still works with server controls in MVC, so no one is stopping you from writing a simple control that just prints a key.

0
source

I prefer to have something like ApplicationFacade. This is what I chose from Mark Dickinson when we worked together.

The room is very similar to what Darin offers, except that 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 like this:

<%= ApplicationFacade.MySetting %>
0
source

Source: https://habr.com/ru/post/1719772/


All Articles