Passing parameters to MVC Ajax.ActionLink

岁酱吖の 提交于 2020-01-01 05:39:22

问题


How can I send the value of the TextBox as a parameter of the ActionLink?

I need to use the 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"} )%>

The Contoller/Actions looks like this:

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

Using MVC 2.0


回答1:


How can I send the value of the TextBox as a parameter of the ActionLink?

The semantically correct way of sending input fields values (such as textboxes) to a server is by using an html <form> and not links:

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

Now in your controller action you will automatically get the value of the SomeField input entered by the user:

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

You could of course try to violate the markup semantics and the way HTML is supposed to work by insisting on using an ActionLink even if it is wrong. In this case here's what you could do:

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

and then in a separate javascript file unobtrusively AJAXify this link using jQuery:

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


来源:https://stackoverflow.com/questions/6699301/passing-parameters-to-mvc-ajax-actionlink

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!