简体   繁体   English

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

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

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. 谢谢。

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()) {%>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM