【问题标题】:How to display app.config file in mvc如何在 mvc 中显示 app.config 文件
【发布时间】:2015-10-27 21:25:56
【问题描述】:

我见过一些旧方法来完成此任务,例如 this one

然而,即使这个显示返回:

<%=ConfigurationManager.AppSettings["webpages:Version"].ToString() %>

我假设我可能正在使用 .Net 世界中过时的东西。目标是遍历这些值并将其打包回 log.html 页面中。

【问题讨论】:

  • 本教程调用函数失败。和我在谷歌上发现的控制台应用程序,但没有什么新东西可以让它作为 MVC 应用程序解决方案工作。在示例中,本教程太旧了,它使用

标签: c# model-view-controller web-config app-config


【解决方案1】:

首先,CodeProject 上 90% 的“教程”完全是垃圾,就像您链接到的那样。它的标题(“使用 Javascript 读取 Web.config 的配置设置”)本身就是一个谎言,因为绝对不可能从 JavaScript 读取 web.config。

其次,您似乎正在阅读 ASP.NET WebForms 教程。从寻找 MVC 教程开始,最好是 http://www.asp.net

这在使用 MVC 时非常简单。您创建一个模型来保存值、一个处理请求的操作方法和一个显示模型值的视图。

public class ConfigurationValuesViewModel
{
    public List<KeyValuePair<string, string>> AppSettingsValues { get; private set; }

    public ConfigurationValuesViewModel()
    {
        AppSettingsValues = new List<KeyValuePair<string, string>>();
    }
}

控制器:

public ActionResult GetConfigurationValues()
{
    // Fill the ViewModel with all AppSettings Key-Value pairs
    var model = new ConfigurationValuesViewModel();     
    foreach (string key in ConfigurationManager.AppSettings.AllKeys)
    {
        string value = ConfigurationManager.AppSettings[key];
        model.AppSettingsValues.Add(new KeyValuePair<string, string>(key, value);
    }

    return View(model);
}

还有观点:

@model ConfigurationValuesViewModel

@foreach (var setting in Model.AppSettingsValues)
{
    @setting.Key - @setting.Value
}

【讨论】:

  • 是的,大约 90% 只是 codeProject 上的废话,但我猜 2005 年那个网站很棒。谢谢,这开始更有意义了。
猜你喜欢
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
相关资源
最近更新 更多