在 ASP.NET MVC 中使用 POST 传递变量
我试图在 asp.net MVC 中传递一个字符串变量。我使用断点,所以我看到它确实转到控制器中的正确方法,但发布的变量等于 null。
我的标记:
@{
ViewBag.Title = "TestForm";
}
<h2>TestForm</h2>
@using (Html.BeginForm()) {
<input type="text" id="testinput" />
<input type="submit" value="TestForm" />
}
我的控制器:
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)
{
}
I am trying to pass a string variable inside asp.net MVC. I use breakpoints so I see that it does go to the correct method in the controller, but the variables posted are equal to null.
My markup:
@{
ViewBag.Title = "TestForm";
}
<h2>TestForm</h2>
@using (Html.BeginForm()) {
<input type="text" id="testinput" />
<input type="submit" value="TestForm" />
}
My controller:
public ActionResult TestForm()
{
return View();
}
[HttpPost]
public ActionResult TestForm(string testinput)
{
Response.Write("[" + testinput + "]");
return View();
}
I put the breakpoint inside the second TestForm method and testinput is null....
Am I missing something?
Note: I realize that most of the time I will be using the model to pass data around, but I would like to know that I can pass strings as well.
As part of the same question, how do I pass several variables? Would the method in my controller look like this:
[HttpPost]
public ActionResult TestForm(string var1, var2)
{
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我来说,您似乎设置了 id 而不是名称。我每天都使用 MVC3,所以我不会重现你的示例。 (我醒了 20 个小时编程;)但仍然有动力提供帮助)如果它不起作用,请告诉我。但对我来说,看起来你必须设置“name”属性......而不是 id 属性。尝试一下...如果不起作用,我现在正在等待帮助您。
For me it looks like that you set the id not the name. I use MVC3 every day, so i dont reproduce your sample. (I am awake for 20 hours programming ;) but still motivated to help ) Please tell me if it dont work. But for me it looks like you have to set the "name" property ... not the id property. Try that ... i am waiting right now to help you if it does not work.
另外一点要注意的是,像您这样传递变量并没有什么问题,但更有效的方法是传递强类型视图模型,使您能够利用 MVC 的许多优点:
创建一个新的视图模型:
您的测试控制器:
您的视图:
On a slightly separate note there is nothing wrong with passing variables like you are, but a more efficient way would be to pass around a strongly typed view model allowing you to take advantage of many aspects of MVC's goodness:
Create a new view model:
Your test controller:
Your view: