在ASP.NET MVC中使用POST传递变量

我试图在asp.net MVC中传递一个字符串变量。 我使用断点,所以我看到它确实转到控制器中的正确方法,但发布的变量等于null。

我的标记:

@{ ViewBag.Title = "TestForm"; } 

TestForm

@using (Html.BeginForm()) { }

我的控制器:

 public ActionResult TestForm() { return View(); } [HttpPost] public ActionResult TestForm(string testinput) { Response.Write("[" + testinput + "]"); return View(); } 

我将断点放在第二个TestForm方法中,testinput为null ….我错过了什么吗?

注意:我意识到大多数时候我将使用模型传递数据,但我想知道我也可以传递字符串。

作为同一问题的一部分,我如何传递几个变量? 我的控制器中的方法是这样的:

 [HttpPost] public ActionResult TestForm(string var1, var2) { } 

对我来说,看起来你设置的id不是名字。 我每天都使用MVC3,所以我不会重现你的样本。 (我醒了20个小时编程;)但仍然有动力去帮助)请告诉我它是否不起作用。 但对我来说,看起来你必须设置“name”属性…而不是id属性。 试试……我现在正等着帮助你,如果它不起作用。

   

在一个稍微单独的注释中,传递变量就像你一样没有错,但更有效的方法是传递一个强类型的视图模型,让你可以利用MVC的优点的许多方面:

  • 强烈类型的观点
  • MVC模型绑定
  • Html助手

创建一个新的视图模型:

 public class TestModel { public string TestInput { get; set; } } 

你的测试控制器:

  [HttpGet] public ActionResult TestForm() { return View(); } [HttpPost] public ActionResult TestForm(FormCollection collection) { var model = new TestModel(); TryUpdateModel(model, collection); Response.Write("[" + model.TestInput + "]"); return View(); } 

你的观点:

 @model .Models.TestModel @{ Layout = null; }    TestForm   
@using(Html.BeginForm()) {
@Html.LabelFor(m => m.TestInput)
@Html.TextBoxFor(m => m.TestInput)
}