簡體   English   中英

在asp.net網頁上顯示隨機報價

[英]Show a random quote on asp.net web page

我正在使用一個使用母版頁的ASP.NET(C#)Web項目。

我正在尋找一種簡單的方法來在每次加載頁面時顯示隨機客戶報價。

由於這是一個相當簡單的Web項目,我想遠離將引號存儲在數據庫中。 目前項目不需要數據庫連接,所以我想保持它盡可能簡單 - 也許將引號存儲在XML文件中,使用XmlTextReader讀取文件?

任何建議表示贊賞。

謝謝

編輯:我需要存儲並提取報價和客戶名稱。

如果你想要簡單:將它存儲為純文本文件,每個引號用換行符分隔,使用File.ReadAllText()讀取整個文件,在換行符上拆分以生成數組,並選擇該數組的隨機索引你的報價。

示例文件:

引用1等等等等等等。
引用2 lorem ipsum dolor ...

示例代碼:

string[] quotes = File.ReadAllText("path/to/quotes.txt")
          .Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
string randomQuote = quotes[new Random().Next(0, quotes.Length)];

使用LINQ可能就像這樣簡單:

XElement xml = new XElement("quotes",
    new XElement("quote",
        new XElement("customer", "Customer #1"),
        new XElement("text", "Quote #1")),
    new XElement("quote",
        new XElement("customer", "Customer #2"),
        new XElement("text", "Quote #2")),
    new XElement("quote",
        new XElement("customer", "Customer #3"),
        new XElement("text", "Quote #3")),
    new XElement("quote",
        new XElement("customer", "Customer #4"),
        new XElement("text", "Quote #4")),
    new XElement("quote",
        new XElement("customer", "Customer #5"),
        new XElement("text", "Quote #5"))
);

//XElement xml = XElement.Load("filename"); // use file instead of above
var result = xml.Elements()
                .OrderBy(r => System.Guid.NewGuid())
                .Select(element => new { 
                        Customer = element.Element("customer").Value,
                        Quote = element.Element("text").Value
                    })
                .First();

Console.WriteLine("{0} : {1}", result.Customer, result.Quote);    

您的文件結構如下:

<quotes>
  <quote>
    <customer>Customer #1</customer>
    <text>Quote #1</text>
  </quote>
  <quote>
    <customer>Customer #2</customer>
    <text>Quote #2</text>
  </quote>
  <quote>
    <customer>Customer #3</customer>
    <text>Quote #3</text>
  </quote>
  <quote>
    <customer>Customer #4</customer>
    <text>Quote #4</text>
  </quote>
  <quote>
    <customer>Customer #5</customer>
    <text>Quote #5</text>
  </quote>
</quotes>

你可以使用XElement xml = XElement.Load("filename");加載它XElement xml = XElement.Load("filename");

使用上面的xml變量,前面的代碼以相同的方式使用(注釋掉代碼)。

Guid可以工作,但你也可以在類中定義一個靜態隨機變量: public static Random rand = new Random(); 然后將代碼更改為:

int count = xml.Elements().Count();
var randomQuote = xml.Elements()
                     .OrderBy(i => rand.Next(0, count))
                     .Select(element => new { 
                        Customer = element.Element("customer").Value,
                        Quote = element.Element("text").Value
                      })
                     .First();

Console.WriteLine("{0} : {1}", result.Customer, result.Quote); 

我相信你回答了你自己的問題。 您可以將引號存儲在xml文件中,然后將它們添加到數組中,並一次從數組中顯示一個值...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM