3

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

 <script type="text/javascript">
      function getname() {
           return $("#first_name").val();
       }
</script>

I tried above code. Its also giving error

getname() does not exist in the current context

3
  • Your will need javascript/jquery to get the value of the textbox and then update the url Commented Jul 23, 2015 at 8:10
  • @stephenmuecke tried the same as edited part in the question Commented Jul 23, 2015 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. Commented Jul 23, 2015 at 8:19

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

how will i create the url if i need to pass some model value also?
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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.