如何将文本框中输入的值传递给操作方法

时间:2013-10-10 05:37:09

标签: asp.net-mvc asp.net-mvc-4

我正在使用MVC构建一个Movies应用程序。 Visual Studio自动为我创建了CRUD。现在,我正在尝试为用户构建搜索功能。这是我写的代码:

@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 个答案:

答案 0 :(得分:2)

您需要为输入字段命名:

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

然后在您的Controller中确保它有一个字符串参数:

在MoviesController中

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

注意:表单字段名称必须与控制器中预期的参数匹配。如果需要“模型”,则映射到模型属性。

答案 1 :(得分:2)

模型

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

使您的视图强类型并使用

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

控制器

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

希望这有帮助。

相关问题