C# 在提交点击时从 asp.net mvc 文本框获取价值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1355547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:33:14  来源:igfitidea点击:

Getting Value from an asp.net mvc textbox on submit click

c#asp.net-mvc

提问by Josh

How do I retrieve the value of a textbox in asp.net mvc to store the value on to some variable?

如何在 asp.net mvc 中检索文本框的值以将值存储到某个变量?

I have a textbox like this <%=Html.TextBox("testbox") %>on the index view page.

<%=Html.TextBox("testbox") %>在索引视图页面上有一个这样的文本框 。

I have a button like this <input type="submit" />

我有一个这样的按钮 <input type="submit" />

I'm using the default view page which comes when you open a new mvc app.

我正在使用打开新 mvc 应用程序时出现的默认视图页面。

Thanks.

谢谢。

采纳答案by griegs

In your controller;

在您的控制器中;

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Search(FormCollection collection)
{
  String g = collection["textFieldname"]
}

or you could use;

或者你可以使用;

TryUpdateModel(modelName);

The above is the prefered solution. If you need more info on TryUpdateModel then post a comment and I'll flesh it out for you.

以上是首选的解决方案。如果您需要有关 TryUpdateModel 的更多信息,请发表评论,我会为您充实。

EDIT:

编辑:

Rather than explain it let me simply show you;

与其解释,不如让我简单地向您展示;

In your controller:

在您的控制器中:

public class MyFormViewModel
{
  public string myInput {get; set;}
}

public ActionResult Search()
{
  MyFormViewModel fvm = new MyFormViewModel();
  return View(fvm);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Search(FormCollection collection)
{
  MyFormViewModel fvm = new MyFormViewModel();
  TryUpdateModel<MyFormViewModel>(fvm);

  string userInput = fvm.myInput;
}

Then in your view;

那么在你看来;

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<YOURNAMESPACE.Controllers.MyFormViewModel>" %>

<%= Html.TextBox("myInput", Model.myInput) %>

Notice two things.

注意两点。

The page is inheriting from your model/class defined in the controller. Not the best place for it but as an example it'll do.

该页面继承自控制器中定义的模型/类。不是最好的地方,但作为一个例子,它会做。

The other thing is that the text box is name the same as the property in the model. In this case myInput.

另一件事是文本框的名称与模型中的属性相同。在这种情况下 myInput.

When the controller does UpdateModel it'll reflection the thing out and match up the textbox name with the name of the field within your form view model.

当控制器执行 UpdateModel 时,它会反射出事物并将文本框名称与表单视图模型中的字段名称相匹配。

Make sense?

有道理?

EDIT 2

编辑 2

Also don't forget to wrap the button and your field in a;

也不要忘记将按钮和您的字段包装在一个;

<% using (Html.BeginForm()) {%>