Josh
Josh

Reputation: 13818

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?

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

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

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

Thanks.

Upvotes: 6

Views: 20743

Answers (1)

griegs
griegs

Reputation: 22760

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.

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.

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.

Make sense?

EDIT 2

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

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

Upvotes: 8

Related Questions