Getting value from asp.net mvc text field when sending a click

How to get textbox value in asp.net mvc to save value for some variable?

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

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

I use the default view page that appears when you open a new mvc application.

Thanks.

+6
c # asp.net-mvc
source share
1 answer

In your controller

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

or you can use;

 TryUpdateModel(modelName); 

The above solution is preferred. If you need more information about TryUpdateModel then post a comment and I will use it for you.

EDIT:

Instead of explaining this, let me just 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 opinion,

 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<YOURNAMESPACE.Controllers.MyFormViewModel>" %> <%= Html.TextBox("myInput", Model.myInput) %> 

Pay attention to two things.

The page inherits from your model / class defined in the controller. Not the best place for him, but as an example it will.

Another thing is that the text field is called the same as the property in the model. In this case, myInput.

When the controller does an UpdateModel, it will reflect this thing and match the name of the text field with the name of the field in your form view model.

Make sense?

EDIT 2

Also do not forget to wrap the button and your field in <; p>

 <% using (Html.BeginForm()) {%> 
+8
source share

All Articles