asp.net-mvc – 使用MVC时,如何调用Controller Action和Pass Text Box值?

如何在使用 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按钮和对该Action的AJAX调用来实现它,但我希望有另一种方法可以使用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并向下滚动到“操作方法参数”部分

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....