When using MVC, how to call a Controller Action and Pass Text Box values?

The Light picture The Light · Feb 10, 2012 · Viewed 8.7k times · Source

How to read from a text box value when using Html.ActionLink so that the value can be passed to the action?

I have the below code:

<table>
        <tr>
            <th>
                Consumer Key:
            </th>
            <td>
                @Html.TextBox("ConsumerKey")
            </td>
        </tr>
        <tr>
            <th>
                Consumer Secret Key:
            </th>
            <td>@Html.TextBox("ConsumerSecretKey")
            </td>
        </tr>
        <tr>
        <th>
        </th>
        <td>@Html.ActionLink("Retreive Access Tokens", "/Retrieve"</td>
        </tr>
    </table>

Basically, I'd need to call the Controller Action and pass the text box values.

How would that be possible with MVC?

I know I can implement it using just an html button and an AJAX call to that Action but I hoped there would be another way using MVC controls.

Answer

layne picture layne · Feb 10, 2012

By putting your code inside the Html.BeginForm("Retrieve", "Twitter") block, the html that is rendered to the browser will be enclosed inside a form-tag, something like:

<form method="POST" action="/Retrieve/Twitter">
    <table>...</table>
</form>

Then when you click on the submit button the form, along with all the values in the text boxes will be posted to you MVC application. Then MVC does the work of mapping these form values (the text boxes created using @Html.TextBox("ConsumerSecretKey") and their values) to the parameters of your controller actions.

In your case, roughly the following will be rendered to the browser (the action link will need to be changed to an input of type "submit," as I have done below:

<form method="POST" action="/Retrieve/Twitter">
    <table>
        <tr>
            <th>
                Consumer Key:
            </th>
        <td>
            <input id="ConsumerKey" name="ConsumerKey" type="text" value="" />
        </td>
    </tr>
    <tr>
        <th>
            Consumer Secret Key:
        </th>
        <td>
            <input id="ConsumerSecretKey" name="ConsumerSecretKey" type="text" value="" />
        </td>
    </tr>

    <td><input type="submit" id="Retrieve" value="Retreive Access Tokens" /></td>

    </tr>

</table>

</form>


When this is posted back to your Application the text you entered into the text boxes (rendered as tags) would map to the parameters of your action method matching their name:

public ActionResult Retrieve(string consumerKey, string consumerSecretKey)
{
    //action method code here
}


The concept at work here is called model-binding. See Controllers and Action Methods in ASP.NET MVC Applications and scroll down to the "Action Method Parameters" section for an overview