如何在ASP.NET MVC 3中使用@html.actionlink传递文本框的值

14
如何在 asp.net mvc3 中使用 @html.actionlink 传递文本值?
4个回答

19

这里的所有答案都不起作用。已接受的答案不能像普通操作链接一样刷新页面;其余答案根本不起作用,或要求您放弃原来的问题并停止使用 ActionLink

MVC3/4

您可以使用ActionLink方法的htmlAttributes来实现您想要的功能:

Html.ActionLink("My Link Title", "MyAction", "MyController", null, new { onclick = "this.href += '&myRouteValueName=' + document.getElementById('myHtmlInputElementId').value;" })

MVC5

以下错误已被报告,但我尚未验证:

检测到可能存在危险的 Request.Path 值


1
如果您在MVC5或更高版本中遇到危险的Request.Path错误,这是由于增强的安全性,因为默认情况下URL不允许使用&符号。您可以将以下内容添加到web.config文件中,以允许它(列表中的任何内容都不允许):<httpRuntime requestPathInvalidCharacters=",*,%,:,\,?" /> - guytz72

6
为了将数据从客户端传递到服务器,您可以使用HTML表单:
  @using (Html.BeginForm(actionName,controllerName)) {
    <input type="text" name="myText"/>
    <input type="submit" value="Check your value!">
}

请确保在您的控制器方法中捕获myText变量。

应该包含如何实现:string myText = Request.Form["myText"].Value; - vapcguy

5

不要使用 @Html.actionlink 来传递您的值,尝试使用 jQuery 将您的文本框值传递到控制器:

$(function () {
    $('form').submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: { search: $('#textboxid').val()},
            success: function (result) {
                $('#mydiv').html(result);
            }
        });
        return false;
    });
});

这段代码会将您的文本框值发送到控制器,并返回输出结果,该结果将加载在“mydiv” div中。

页面没有刷新,需要编写另一种方法来刷新。 - pavan kumar

-4

你可以使用这段代码(YourValue = TextBox.Text)

Html.ActionLink("Test", new { controller = "YourController", action = "YourAction", new { id = YourValue }, null );

public class YourController : Controller
{
        public ActionResult YourAction(int id)
        {
            return View("here your value", id);
        }
}

尝试使用 <%=Html.TextBoxFor(x => x.Property, new { id = "IdTextBox" })%>。 - Aghilas Yakoub
@Html.TextBoxFor(x => x.name, new { id = "IdTextBox" }) @Html.ActionLink("测试", "创建", "主页", new { id = "IdTextBox" }), 但是它没有起作用. :( - kiransh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接