This article
will show you how you can pass, send or access view textbox value in controller in asp.net
mvc. In this article i will explain how you can pass TextBox, TextBoxFor and
Input textbox value from view to controller end on submit button click.
So for this first we will create a new asp.net mvc application, and add a controller class. In this we will take an actionresult method and create a view.
So for this first we will create a new asp.net mvc application, and add a controller class. In this we will take an actionresult method and create a view.
[HttpGet]
public ActionResult Index()
{
return View();
}
|
View of above method
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
|
TextBox: For this add a @Html.TextBox razor control.
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.TextBox("StudentName")
<input type="submit" value="Submit" />
}
|
Now go to controller end and in post method add the below bode as show below.
[HttpPost]
public ActionResult Index(string StudentName)
{
return View();
}
|
Please check the highlighted part of the above code. In this post method i have passed a parameter named as StudentName Which is exactly same as the name of the control. If you make the control name different you will not be able to access the control value. Now run the application and check output by outing the break point.
TextBoxFor: First we will create a model class as shown
below.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
namespace StateManagement.Models
{
public class StudentModel
{
public string StudentName { get; set; }
}
}
|
For this
add a @Html.TextBoxFor razor control with model.
@model StateManagement.Models.StudentModel
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.TextBoxFor(m => m.StudentName)
<input type="submit" value="Submit" />
}
|
Now at controller end we will pass the model class name as parameter in post method.
[HttpPost]
public ActionResult Index(string StudentName)
{
return View();
}
|
Now put the break point and run the application.
HTML Input: In this first you need to add an input control
as shown below.
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<input type="text" name="StudentName" />
<input type="submit" value="Submit" />
}
|
Now at controller
end put the below code.
[HttpPost]
public ActionResult Index(string StudentName)
{
return View();
}
|
Here you
will see that the parameter name is same as the text input control. Now run the
application and click on submit.
As you
click on submit button you break point will hit and you below get your value in
parameter.
0 comments:
Please let me know your view