Pieter de Vries
Pieter de Vries

Reputation: 825

How to get the value of a text-box in MVC easily

Hey guys I am new to Stackoverflow and new to MVC.
I am Using vb but c# might help too.
I want to get the username from a login form I created.
I know my code doesn't work but for demonstration purposes I entered it. How can I get the UserName textbox value in my controller.

My controller

Sub Login()
    Dim rvdDB As New RVDDataClassesDataContext
    Dim Employees = From Employee In rvdDB.Employees Where Employee.EmpID = TUserName
End Sub

My View page

@ModelType RVDLoginMVC.Login
@Code
    ViewData("Title") = "Login"
End Code

<div id="MainLogin" style="text-align:center">
    <img src="~/Models/rvd_logo.jpg" alt="Rogue Valley Door" />
    <p>Username: <input id="TUserName" name="TUserName" type="text" /></p>
    <p>Password: <input id="TPassword" name="TPassword" type="password" /></p>
    <input type="button" value="Login" onclick="location.href='@Url.Action("Login", "Login")'" />
</div>

Upvotes: 0

Views: 1060

Answers (2)

user2021740
user2021740

Reputation: 174

You can access textbox value by passing in Controller FormCollection parameter like given below.

public ActionResult Login(FormCollection _frmCollection)
{
  string _userName=_frmCollection["TUserName"];
}

Upvotes: 0

Craig W.
Craig W.

Reputation: 18155

Your view declares a model which I'm assuming has the username and password as properties. You should be creating controls that bind to the model properties and then taking an instance of the model in your Login() method.

My VB.NET is pretty rusty so you may have to play with this a bit.

Sub Login(viewModel as RVDLoginMVC.Login)
    Dim rvdDB As New RVDDataClassesDataContext
    Dim Employees = From Employee In rvdDB.Employees Where Employee.EmpID = viewModel.Username
End Sub

Then in the View do this. This is the C# flavor of the Razor syntax, I've never done a vbhtml so I don't know the VB.NET flavor.

<p>Username: @Html.TextBoxFor( model => model.Username )</p>
<p>Password: @Html.PasswordFor( model => model.Password )</p>

Upvotes: 1

Related Questions