2016-07-13 34 views
0

我有許多.cshtml頁面可用於我的MVC項目的視圖文件夾。在我的佈局頁面中有可用的搜索選項,所以當有人用任何詞搜索時,然後我想在所有.cshtml頁面中搜索該詞並返回視圖名稱。 我如何在MVC中實現這一點?如何在mvc中搜索整個視圖文件夾中的任何單詞

+1

你需要一個搜索索引引擎,如[Lucene的.NET(https://www.nuget.org/packages/Lucene.Net/)或[彈性搜索](https://damienbod.com/2014/10/01/full-text-search-with-asp-net-mvc-jquery-autocomplete-and-elasticsearch/)或許多第三方搜索索引之一蜜蜂。 MVC中沒有內容可以進行搜索。另外,你可能不想搜索你的*視圖*,因爲通常大部分內容都是通過視圖模型添加到視圖中的。您應該將您放入視圖模型的*內容編入索引。 – NightOwl888

+0

您的意思是我們需要將整個文本索引到數據庫,如彈性搜索和從那裏搜索。對? –

+0

是的。爲了獲得最佳性能,您應該在搜索時帶外索引。您只需索引一次網站,然後搜索多次。 – NightOwl888

回答

1

一個可能的方式做到這一點:

string path = Server.MapPath("~/Views"); //path to start searching. 
if (Directory.Exists(path)) 
{ 
    ProcessDirectory(path); 
} 
//Loop through each file and directory of provided path. 
public void ProcessDirectory(string targetDirectory) 
{ 
    // Process the list of files found in the directory. 
    string[] fileEntries = Directory.GetFiles(targetDirectory); 
    foreach (string fileName in fileEntries) 
    { 
      string found = ProcessFile(fileName); 
    } 
    //Recursive loop through subdirectories of this directory. 
    string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory); 
    foreach (string subdirectory in subdirectoryEntries) 
    { 
      ProcessDirectory(subdirectory); 
    } 
} 
//Get contents of file and search specified text. 
public string ProcessFile(string filepath) 
{ 
    string content = string.Empty; 
    string strWordSearched = "test"; 

    using (var stream = new StreamReader(filepath)) 
    { 
     content = stream.ReadToEnd(); 
     int index = content.IndexOf(strWordSearched); 
     if (index > -1) 
     { 
       return Path.GetFileName(filepath); 
     } 
    } 
} 
+0

謝謝,這解決了我的問題。 –

相關問題