微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐