pass value of a textbox from view to controller using actionlink
pass value of a textbox from view to controller using actionlink
In my form I have a textbox as below
@Html.TextBox("first_name")
I need to pass the value of this textbox to controller through a actionlink.
I tried the below
@Html.ActionLink("View", "view_Details", new { name = first_name})
but this is giving error
"first_name" does not exist in the current context
Is this possible using a Actionlink?
My controller signature is
public ActionResult view_Details(string name)
{
return View();
}
Edited
@Html.ActionLink("View", "view_Details", new { name = getname()})
function getname() {
return $("#first_name").val();
}
I tried above code. Its also giving error
getname() does not exist in the current context
@stephenmuecke tried the same as edited part in the question
– Sachu
Jul 23 '15 at 8:14
That's because razor code is parsed on the server before its send to the view.
getname()
is a client side method which does not exist at that point. I'll post a answer shortly showing how you can do this.– Stephen Muecke
Jul 23 '15 at 8:19
getname()
1 Answer
1
You need javascript/jquery to get the value of the textbox and then update the url you want to redirect to
Html
@Html.ActionLink("View", "view_Details", new { id = "myLink" }) // add id attribute
Script
$('#myLink').click(function() {
var firstname = $('#first_name').val(); // get the textbox value
var url = $(this).attr('href') + '?name=' + firstname; // build new url
location.href = url; // redirect
return false; // cancel default redirect
});
Side note: further to you edit, the reason you receive that error is that razor code (the @Html.ActionLink()
is parsed on the server before its sent to the view but getname()
is a client side method which does not exist at that point - i.e it does not exist in the current context
@Html.ActionLink()
getname()
how will i create the url if i need to pass some model value also?
– Sachu
Jul 23 '15 at 8:32
Do you mean say the
ID
property of the model? - in which case you could add var id = '@Model.ID';
and then var url = $(this).attr('href') + '?name=' + firstname + '&id=' + id;
– Stephen Muecke
Jul 23 '15 at 8:34
ID
var id = '@Model.ID';
var url = $(this).attr('href') + '?name=' + firstname + '&id=' + id;
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Your will need javascript/jquery to get the value of the textbox and then update the url
– Stephen Muecke
Jul 23 '15 at 8:10