将输入值传递给操作(ASP.Net MVC 3)

gre*_*mul 16 razor asp.net-mvc-3

我在View中有代码:

@using (Html.BeginForm("MyAction", "MyController")
{
    <input type="text" id="txt" />          
    <input type="image" src="/button_save.gif" alt="" />
}
Run Code Online (Sandbox Code Playgroud)

如何将txt的值传递给我的控制器:

[HttpPost]
public ActionResult MyAction(string text)
{
 //TODO something with text and return value...
}
Run Code Online (Sandbox Code Playgroud)

Bra*_*don 46

为输入命名,并确保它与操作的参数匹配.

<input type="text" id="txt" name="txt" />

[HttpPost]
public ActionResult MyAction(string txt)
Run Code Online (Sandbox Code Playgroud)

  • 哦,是的!当然!我忘了使用名字...而且我忘记了输入的名称必须与我的动作中的参数名称相同.谢谢! (3认同)

Ada*_*SFT 10

在表单内添加一个输入按钮,以便您可以提交

<input type=submit />

在您的控制器中,您有三种获取此数据的基本方法1.将其作为与控件名称相同的参数

public ActionResult Index(string text)
{

}

OR

public ActionResult Index(FormsCollection collection)
{
//name your inputs something other than text of course : )
 var value = collection["text"]
}

OR

public ActionResult Index(SomeModel model)
{
   var yourTextVar = model.FormValue; //assuming your textbox was inappropriately named FormValue
}