0

I have an input and a button. input's value supposed to be passed to @url.Action like description in code below:

<input class="in-class" id="textbox" type="text" runat="server" />
<button class="btn-class" id="press" type="button" onclick="location.href='@Url.Action("Index", "Home", new {id = /*Value Of textbox*/ })'" >click here</button>

As I mentioned in code, /*Value Of textbox*/ should be input's current value.

Mohammad Farahi
  • 1,006
  • 4
  • 14
  • 38

3 Answers3

2

Change the href value with jQuery or JavaScript like this:

     <button class="btn-class" id="press" type="button" onclick="changeHref()" >click here</button>

   function changeHref(){
         var url = '@Url.Action("Index", "Home")';
         var txtVal = $('#textbox').val();
         window.location.href = url + '/?txtVal=' + txtVal;
   }
  • Forgot the query string. You'll have to add ?txtVal= after the '/'. I updated the code –  Jul 25 '18 at 19:23
  • Is it hitting the Index method inside the Home controller? Put a breakpoint inside the method to see if you even go back to the server. If not, then it's the url that's being set. –  Jul 25 '18 at 19:27
  • they both wont hit breakpoint, in the first place ('/') it opens just txtVal as a link, but when I Use '/?txtVal=' nothing happens. – Mohammad Farahi Jul 25 '18 at 19:33
  • 1
    Try, window.location.href = url + '?id=' + txtVal; – Skye MacMaster Jul 25 '18 at 19:37
  • use post or get instead of window.location then: $.post(url, {txtVal: txtVal}); –  Jul 25 '18 at 19:40
  • post or get is for ajax. window.location is fine if he wants to navigate to a new page. – Skye MacMaster Jul 25 '18 at 19:42
  • Your url will be wrong. You can't use @url.Action in js function. Try to send url.action as parameter from html onclick="changeHref(url.action(controller, action))" – KreminT Jul 25 '18 at 20:59
2

I use this form

<input type="text" id="txtValue" /> <input type="button" value="Detail" onclick="location.href='@Url.Action("Action", "Home")?Value=' + $('#txtValue').val()" />

or you cant write this in jquery function.

Jsperk
  • 124
  • 1
  • 11
1

I preferred using jQuery click handler since you have button ID and following standard event registration model to separate HTML & JS:

HTML

<input class="in-class" id="textbox" type="text" />
<button class="btn-class" id="press" type="button">click here</button>

JS

$('#press').click(function () {
   var url = '@Url.Action("Index", "Home")';
   var textValue = $('#textbox').val();

   window.location.href = url + '?id=' + textValue;
});

PS: No need to use runat="server" attribute in MVC since Razor doesn't require it.

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61