achu
achu

Reputation:

Getting an input value or JavaScript variable in ASP.NET MVC Ajax.ActionLink

I want to pass an input control value (say textbox1.value or a javascript variable) to a controller action method (as a parameter) without a form post (using Ajax.ActionLink). Please see the code below.

Is it possible to assign something like new {name = textbox1.value} in Ajax.ActionLink.

View

<input type="text" id="textbox1" />
<%= Ajax.ActionLink("mylink", "linkfunction", new {name = textbox1.value}, new AjaxOptions { UpdateTargetId = "result"}) %>
<span id="result"></span>

and controller action is:

public string linkfunction(string name)
{
    return  DateTime.Now.ToString();
}

Upvotes: 3

Views: 5362

Answers (3)

Peter Smith
Peter Smith

Reputation: 5550

I had a similar problem. Once it was pointed out to me that these functions return strings the rest fell into place - so, try the following

Ajax.ActionLink("mylink", "linkfunction", 
    new {name = __MyValue__}, new AjaxOptions 
    { UpdateTargetId = "result"}).Replace("__MyValue__", textbox1.value)

I haven't tested this snippet but something like this worked very well for me.

Good luck.

Upvotes: 0

davekaro
davekaro

Reputation: 6441

I had this same problem, except I was using jQuery to make my ajax request:

$('#ajax-content').load('<%= this.Url.Action("Details", "Page", new { id = someJavascriptVariable }) %>');

I got it to work like this:

$('#ajax-content').load('<%= this.Url.Action("Details", "Page", ) %>' + '/' + someJavascriptVariable);

Or, in your case, it might look like this:

$('#ajax-content').load('<%= this.Url.Action("Details", "Page", ) %>' + '?name=' + textbox1.value);

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190941

This is similar to this:

ASP.NET MVC : AJAX ActionLink- Target an HTML attribute

Plus, you don't need to pass in the control name into your Action.

Upvotes: 1

Related Questions