Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get HTML controls value in Controller

Tags:

asp.net-mvc

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

like image 887
user2218549 Avatar asked Apr 01 '13 06:04

user2218549


2 Answers

add name attribute to your input fields like:

<input id="txtClientName" name="txtClientName" type="text" />
like image 72
Gurmeet Avatar answered Sep 28 '22 15:09

Gurmeet


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...
}
like image 43
Cengiz Araz Avatar answered Sep 28 '22 15:09

Cengiz Araz