2013-10-10 27 views
1

我正在使用MVC構建電影應用程序。 CRUD是由Visual Studio自動爲我創建的。現在,我正在嘗試爲用戶構建一個搜索功能。這是我寫的代碼:如何將文本框中輸入的值傳遞給操作方法

@using (Html.BeginForm("SearchIndex", "Movies", new {searchString = ??? })) 
{ 
    <fieldset> 
     <legend>Search</legend> 

     <label>Title</label> 
     <input type ="text" id="srchTitle" /> 
     <br /><br /> 
     <input type ="submit" value="Search" /> 
    </fieldset>  
} 

我已經建立了SearchIndex方法與相關視圖。我只是無法找到如何將文本框中輸入的值傳遞給SearchIndex操作方法。 請幫忙。

回答

2

你需要給你的輸入字段的名稱:

<input type="text" id="srchTitle" name="movieToFind" /> 

然後在你的控制器確保它有一個字符串參數:

在MoviesController

[System.Web.Mvc.HttpPost] 
public ActionResult SearchIndex(string movieToFind) 
{ 
    //Controller Action things. 
} 

注:表字段名稱必須與控制器中預期的參數相匹配。或者如果預計有'模型',則映射到模型屬性。

2

在你型號

public class Search 
{ 
public String SearchText { get; set; } 
} 

讓您查看強類型和使用

@Html.EditorFor(model => model.SearchText) 

在你控制器

[HttpPost] 
public ActionResult SearchIndex(Search model) 
{ 
String text = model.SearchText; 
} 

希望這有助於。

相關問題