2012-05-11 11 views
1

我正在構建一個基於WebMatrix的網站,並且我忽略了某些內容。一些事情,只是沒有發生在我身上。如果搜索框位於_SiteLayout頁面(標頭DIV)中,如何將搜索結果返回給用戶

我的網站是這樣構成的,每個頁面都引用頁眉和頁腳的_SiteLayout.cshtml頁面。例如:

_SiteLayout.cshtml

<html> 
<head> 
</head> 
<body> 
    <div id="Container"> 
      <div id="heading"> 
       <input type="text" name="search" value="search" id="searchbox" /> 
      </div> 
      @RenderBody() <!-- display Default.cshtml content --> 
     <div id="footer"><p>stuff here</p></div> 
    </div> 
</body> 
</html> 

Default.cshtml

@{ 
    Layout = "~/_SiteLayout.cshtml"; 
} 
<p> 
I want to display search results in the Default.cshtml (homepage) page, but I don't know how to if the search form is inside the SiteLayout page. How to do this? 
</p> 

所以,我的問題是要顯示在Default.cshtml搜索結果(主頁)頁面,但我不知道如何搜索表單在SiteLayout頁面內。

我該如何去做這件事?

回答

3

您需要將該搜索輸入中的信息發佈到服務器。一旦你獲得了數據,你可以使用它來定位你知道將在子視圖中的HTML元素。

This article來自jQuery文檔幫助我。我的數據來自JSON響應,但該示例顯示瞭如何使用jQuery獲取結果響應並將其添加到特定元素(在此例中爲<body>,但您可以輕鬆創建帶有ID的div的「搜索結果」,並與#search-results目標吧):

$.getJSON('ajax/test.json', function(data) { 
    var items = []; 

    $.each(data, function(key, val) { 
    items.push('<li id="' + key + '">' + val + '</li>'); 
    }); 

    $('<ul/>', { 
    'class': 'my-new-list', 
    html: items.join('') 
    }).appendTo('body'); // Here, you could append your items to #search-results 
}); 

然後,它會達到所有的意見,包括與搜索結果的ID的部分,但如果不存在的話,那麼數據不會出現在任何地方。該腳本應該位於單獨的文件中,並在您的主站點佈局中引用。

+0

哦,謝謝!非常好的解決方案@Brandon :-) – shane

相關問題