如何在使用
Html.ActionLink时从文本框中读取值,以便将值传递给操作?
<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>
基本上,我需要调用Controller Action并传递文本框值.
如何使用MVC实现这一目标?
解决方法
通过将代码放在Html.BeginForm(“Retrieve”,“Twitter”)块中,呈现给浏览器的html将封装在form-tag中,如:
<form method="POST" action="/Retrieve/Twitter"> <table>...</table> </form>
然后当您单击提交按钮时,表单以及文本框中的所有值都将发布到您的MVC应用程序.然后MVC完成将这些表单值(使用@ Html.TextBox(“ConsumerSecretKey”)创建的文本框及其值)映射到控制器操作的参数的工作.
在您的情况下,大致会将以下内容呈现给浏览器(操作链接将需要更改为“提交”类型的输入,如下所示:
<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>
当这个回发到您的应用程序时,您在文本框中输入的文本(呈现为标记)将映射到与其名称匹配的操作方法的参数:
public ActionResult Retrieve(string consumerKey,string consumerSecretKey) { //action method code here }
这里的概念称为模型绑定.有关概述,请参见Controllers and Action Methods in ASP.NET MVC Applications并向下滚动到“操作方法参数”部分