【问题标题】:Passing parameters to MVC Ajax.ActionLink将参数传递给 MVC Ajax.ActionLink
【发布时间】:2011-10-05 16:07:23
【问题描述】:

如何将 TextBox 的值作为 ActionLink 的参数发送?

我需要使用 Html.TextBoxFor

<%= Html.TextBoxFor(m => m.SomeField)%>
<%= Ajax.ActionLink("Link Text", "MyAction", "MyController", new { foo = "I need here the content of the textBox, I mean the 'SomeField' value"}, new AjaxOptions{ UpdateTargetId = "updateTargetId"} )%>

Contoller/Actions 如下所示:

public class MyController{
   public ActionResult MyAction(string foo)
   {      
      /* return your content */   
   }
}

使用 MVC 2.0

【问题讨论】:

标签: asp.net-mvc-2 parameters asp.net-ajax actionlink


【解决方案1】:

如何将 TextBox 的值作为 ActionLink 的参数发送?

将输入字段值(例如文本框)发送到服务器的语义正确方法是使用 html &lt;form&gt; 而不是链接:

<% using (Ajax.BeginForm("MyAction", "MyController", new AjaxOptions { UpdateTargetId = "updateTargetId" })) { %>
    <%= Html.TextBoxFor(m => m.SomeField) %>
    <input type="submit" value="Link Text" />
<% } %>

现在,在您的控制器操作中,您将自动获取用户输入的 SomeField 输入值:

public class MyController: Controller
{
    public ActionResult MyAction(string someField)
    {      
       /* return your content */   
    }
}

您当然可以通过坚持使用ActionLink 来尝试违反标记语义和HTML 的工作方式,即使它是错误的。在这种情况下,您可以执行以下操作:

<%= Html.TextBoxFor(m => m.SomeField) %>
<%= Html.ActionLink("Link Text", "MyAction", "MyController", null, new { id = "myLink" }) %>

然后在一个单独的 javascript 文件中使用 jQuery 不显眼地 AJAXify 这个链接:

$(function() {
    $('#myLink').click(function() {
        var value = $('#SomeField').val();
        $('#updateTargetId').load(this.href, { someField: value });
        return false;
    });
});

【讨论】:

  • 嗨,你为什么使用 $(function () { ?为什么不使用 $('#myLink').click 直接?是 $(document).on('click', '# myLink', function() 一样吗?谢谢
猜你喜欢
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多