c# - Ajax post causing 2 actions to run -


i'm new mvc, , problem has been driving me wall. have javascript triggers jquery ajax post when user press tab or enter key in textboxes on form:

<script type="text/javascript">     $(document).ready(function () {         $('#rmanumber, #serialnumber').keydown(function (event) {             if (event.keycode == 13 || event.keycode == 9) {                 var ri = {                     rmanumber: $('#rmanumber').val(),                     serialnumber: $('#serialnumber').val(),                     controlname: event.target.id                 }                   $.ajax({                     type: "post",                     url: "/invoice/barcodescan",                     contenttype: "application/json; charset=utf-8",                     data: json.stringify(ri),                     datatype: "json",                     success: function (data) {                         $('#terminaltype').text(data.terminaltype);                     }                  });             }         });     }); </script> 

here controller looks like. removed code keep things simple:

  public actionresult index()         {          }    [acceptverbs(httpverbs.post)]         public actionresult index(repairinvoice ri)         {          }   [httppost]         public actionresult barcodescan(string rmanumber, string serialnumber, string controlname)          {         } 

the ajax postback causes both barcodescan , index action fire. want index action [acceptverbs(httpverbs.post)] above fire if button pressed on form. possible, or on wrong track?

since comments helped, i'll add answer future visitors...

i can't notice 1 of key inputs you're looking return key. depending on how html form , input set up, return key may causing form post normal. essentially:

  • the javascript code invoking post barcodescan action
  • the html form invoking post index action

the result of former being ignored browser, since page being re-loaded in entirety. regardless of result, action still invoked.

there couple of ways address this:

  • if there submit input you're otherwise using button, can change button , leave form without submit. works forms should javascript-driven , not have default post action, it's hard tell if applies here without knowing more.
  • the javascript code can stop dom event in tracks by calling preventdefault(). jquery functions have parameter event, , you'd call function on event. tell dom end event doesn't "bubble up" form, document, etc.

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -