Passing parameters to MVC Ajax.ActionLink
Asked Answered
N

1

6

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

Neville answered 14/7, 2011 at 20:6 Comment(1)
Your answer : #2596330Emancipator
E
7

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;
    });
});
Electromagnetic answered 14/7, 2011 at 21:24 Comment(1)
Hi, why do you use the $(function () { ? Why not the $('#myLink').click direclty? Is $(document).on('click', '#myLink', function () the same thing? ThanksKira

© 2022 - 2024 — McMap. All rights reserved.