Passing parameters to MVC Ajax.ActionLink

LastCyborg picture LastCyborg · Jul 14, 2011 · Viewed 12.6k times · Source

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

Answer

Darin Dimitrov picture Darin Dimitrov · Jul 14, 2011

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;
    });
});