user2218549
user2218549

Reputation: 155

Get HTML controls value in Controller

I want to get HTML textbox value in controller. Below is my view code

@using (Html.BeginForm("SaveValues", "TestGrid",FormMethod.Post))
{
<table>
 <tr>
    <td>Customer Name</td>
    <td>
        <input id="txtClientName" type="text" />
     </td>
    <td>Address</td>
    <td>
        <input id="txtAddress" type="text" /></td>
    <td>
        <input id="btnSubmit" type="submit" value="Submit" /></td>
    </tr>
</table>}

Please check my controller code below to get the values

[HttpPost]
    public ActionResult SaveValues(FormCollection collection)
    {
        string name = collection.Get("txtClientName");
        string address = collection.Get("txtAddress");
        return View();
    }

I am getting null values

Upvotes: 7

Views: 31770

Answers (5)

Cengiz Araz
Cengiz Araz

Reputation: 680

If you declare all your controls in the view inside the

@using (Html.BeginForm())
{
//Controls...
}

ASP.NET (WebPages, MVC, RAZOR) uses HTTP protocol as base for the interactions between client and server. And to make HTTP pass client-side values to the server-side all HTML elements must have name attributes defined. The id attribute in HTML element is just for the front-end use. (CSS, JavaScript, JQuery, etc.). See the below lines of code for a working example;

<input type="text" name="zzzz" id="xxxx"/>

Then in the controller you can access the controls with FormCollection object. It includes all controls described with a name attribute.

//
// POST:
[HttpPost]
public ActionResult CreatePortal(FormCollection formCollection)
{
    // You can access your controls' values as the line below.
    string txtValue = formCollection["zzzz"]; 

    //Here is you code...
}

Upvotes: 8

user3065134
user3065134

Reputation: 21

To Get the HTML Control Value in the Controller through Form collection, You need to add "name" attribute to your HTML Controls.

Upvotes: 1

Dumisani
Dumisani

Reputation: 3038

Try this:

Request.Form["controlID"]

Upvotes: 0

Saeed Afshari
Saeed Afshari

Reputation: 949

I Asp.net MVC Html.BeginForm use name attribute of html element for serializing. Then you have to fill name attribute of html element

Upvotes: 0

Gurmeet
Gurmeet

Reputation: 3314

add name attribute to your input fields like:

<input id="txtClientName" name="txtClientName" type="text" />

Upvotes: 7

Related Questions