Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

asp.net mvc - 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()})

 <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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...