How to store a string in xml file and use it in _Layout in MVC

时间:2015-06-15 15:15:44

标签: c# xml asp.net-mvc asp.net-mvc-4

I'm new here. I've started working my own forum system recently to use as a portfolio. Decided to let the admin of the website set his own name and description for the forum. So first thought was use .ini file to put the string there but C# does not support inis but it does XML files. So I have created a simple XML file for use.

But my question is where do I read all the values from that XML file to send them to _Layout every time.

Because if I send it through the View() from each function in the controller that is not really good.

Can somebody point out where in the website to read the values and send them to the _Layout

3 个答案:

答案 0 :(得分:0)

我的答案不是针对XML,而是针对资源文件。您可以使用它们来注释模型,甚至可以直接在视图中使用它们

以下是有关资源文件http://www.devcurry.com/2013/02/aspnet-mvc-using-resource-files-to.html

的文章

答案 1 :(得分:0)

当然,您可以使用xml,但您也可以使用JSON,它的尺寸更小,现在是一般的社区标准。

无论哪种方式,您都可以使用以下方法在.NET Web应用程序中读取文件:

string viewPath = HttpContext.Current.Server.MapPath("~/Content/Templates/your-xml_file.xml");
                var template = File.ReadAllText(viewPath);

然后在想要读取xml文件的库中使用(或者你可以将它反序列化为一个对象并使用它来使你的内容变得简单,而不是在xml文件的节点中导航。

如果使用JSON数据,可以使用Newtonsoft.Json.JsonConvert类来读取和反序列化。

答案 2 :(得分:0)

Sourced: from this link

web.config(或app.config)是存储自定义字符串的好地方:

  web.config中的

<appSettings>
   <add key="message" value="Hello, World!" />
</appSettings> 
     

in cs:

string str = ConfigurationSettings.AppSettings["message"].toString();