SandSnark
SandSnark

Reputation: 90

Javascript and keyup to pass data to a Controller

My view has a single textbox which captures scans from users. The scans will then be passed without any further user action to another action that will then use the scanned data to complete the transaction. So far, the textbox gets populated with the scan and immediately does redirect but without the contents of the textbox. This is what I have;

View:

<input id="thisText" class="largetext" name="txtScanLabel"  onkeyup="myKeyUp" />

And:

  <script type="text/javascript">
   var tResults = "Test";

       $(function () {
           $('input.largetext').focus();
       });

       $(function () {
           $("#thisText").keyup(myKeyUp);
       });

       function myKeyUp(eventInstance) {
           var myURL = '@Url.Action("ScanResults", "Home")';
           window.location.href = myURL + '?tResults' + encodeURIComponent(tResults);
       }

   </script>

Controller:

    public ActionResult ScanResults(string tResults)
    {

        var test = tResults;                     

        return RedirectToAction("Success");

    }

Upvotes: 0

Views: 2382

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

You have unobtrusively subscribed to the .keyup event handler with jQuery and yet you have used the onkeyup attribute in your DOM. You don't need to do those two things. Using jQuery is enough. So start by cleaning your markup:

<input id="thisText" class="largetext" name="txtScanLabel" />

Also you have hardcoded the tResults value to Test in your javascript. Instead of using this hardcoded value from the global variable (that you could get rid of) you should read the value from the textbox:

function myKeyUp(eventInstance) {
    var myURL = '@Url.Action("ScanResults", "Home")';
    var value = $(this).val();
    window.location.href = myURL + '?tResults=' + encodeURIComponent(value);
}

Notice that using window.location.href will immediately redirect to the ScanResults controller action when the user types something into the input field. You probably want to use AJAX:

function myKeyUp(eventInstance) {
    var myURL = '@Url.Action("ScanResults", "Home")';
    $.ajax({
        url: myURL,
        type: 'POST',
        data: { tResults: $(this).val() },
        success: function(result) {
            // do something with the result returned by the controller action
        }
    });
}

Upvotes: 2

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

You need this perhaps as your "test will NOT work as it is now:

       window.location.href = myURL + '?tResults' + encodeURIComponent(tResults); 

change to

       tResults = $('#thisText').val();
       window.location.href = myURL + '?tResults=' + encodeURIComponent(tResults); 

DO NOT forget that important equal sign in there.

Upvotes: 0

Behnam Esmaili
Behnam Esmaili

Reputation: 5967

you haven't included [HttpPost] Attribute in controler Action.

Upvotes: 0

Related Questions