加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 使用MVC时,如何调用Controller Action和Pass Tex

发布时间:2020-12-16 09:50:42 所属栏目:asp.Net 来源:网络整理
导读:如何在使用 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时从文本框中读取值,以便将值传递给操作?

我有以下代码:

<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并向下滚动到“操作方法参数”部分

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读