2013-07-08 26 views
1

我是MVC的新手,所以我可能無法完全理解如何在PartialView中使用操作,所以請耐心等待。在部分視圖上調用操作

我有一個形式PartialView,我想它提交時的PartialView的控制器上執行相應的操作。我做了這個工作,但是,當我使用

@using (Html.BeginForm()) 
    { 
     <div class="search-box"> 
      @Html.EditorFor(x => x.Keyword) 
      <button type="submit" title="Search" id="searchButton">Search</button> 
     </div> 
    } 

我沒有在URL得到任何參數,我希望人們能夠深層連結到這個搜索。如果我在BeginForm標籤中添加Action和Controller,我會得到一個如下所示的URL:/ LostItems/Index?Keyword = phones,它返回一個404,因爲它是一個PartialView,而不是一個具有路由的View。

我該如何解決這個問題?如果表單在View上而不在PartialView上,那麼它就可以正常工作,因爲URL會路由到頁面上的特定操作。

+0

你不能剛'BeginForm()',你應該指定控制器和動作:'Html.BeginForm( 「行動」, 「控制器」,...)'。這個問題很可能出現在你的行動中 - 你可以發佈它嗎?另外,你說如果放在普通的視圖中,完全相同的HTML代碼就可以工作 - 你可以仔細檢查一下嗎? – andreister

回答

0

你不能有一個動作方法返回一個局部視圖,如果你想直接鏈接到它作爲一個完整的頁面(如/ LostItems /指數?關鍵字=手機)

如果它是一個簡單的一個單詞搜索,那麼不需要爲此創建視圖模型類。

即時猜測你應該僅僅是像

//controller 
public ActionResult Index(string Keyword) 
{ 
    var SearchResults = new List<SearchResult>() 

    // 
    // Get your search results 
    if(!String.IsNullOrEmpty(Keyword)) 
    { 
     SearchResults = GetSearchResults(Keyword) 
      //your code for getting the search results 
    } 
    return View(SearchResults) 
} 

查看:

@model List<SearchResult> 
<h1>Search</h1> 
@using(Html.BeginForm("Index", "ControllerName", FormMethod.Get)) 
{ 
    @Html.Label("Keyword", "Enter your Search Term") 
    @Html.Texbox("Keyword") 
    <input type="submit" value="Submit" /> 
} 

@if(Model.Count > 0) 
{ 
    //display the search results - could be in a partial view, with the model passed though like 
    @Html.Partial("_resultsGrid", Model) 
} 

這應該通過獲取關鍵字是否指定或沒有我想象的工作,但我可能是錯的(在這種情況下需要一些路由來指定默認值)。

替代結構(特別是對於更復雜的搜索)是爲搜索項創建視圖模型,但將搜索結果轉儲到Viewbag中而不是作爲模型(因此searchTerm可以保留爲模型,發表時間,如果它改變)