开发者

Submit form when contents of MVC3 Html.TextBoxFor changes

开发者 https://www.devze.com 2023-03-23 09:53 出处:网络
This should be fairly easy but I\'ve tried a few things with no luck. I have a series of Html.TextBoxFor fields on a page, each inside their own Ajax.BeginRouteForm.Next to each box I have a submit b

This should be fairly easy but I've tried a few things with no luck.

I have a series of Html.TextBoxFor fields on a page, each inside their own Ajax.BeginRouteForm. Next to each box I have a submit button, and this, when clicked, performs the Ajax update as desired.

I'd like to automate this so that when the user changes a value in a field (the onchange event) the form is submitted the same way it currently using using the submit button.

I tried using the htmlattributes to assign a JavaScript function to the onchange event (as shown below) and this causes the form to submit, but it redirects the page instead of working in the ajax fashion (as opposed to clicking the submit button which works correctly).

@(Html.TextBoxFor(model => answer.Value, new { onchange = "document.forms[" + answer.AnswerID + "].submit()" }));

(fortunately my answer.AnswerID is numeric and matches up with the numeric position of开发者_Python百科 the appropriate form in the forms collection; I was referencing them by name but Razor (or something) was htmlencoding my JavaScript code...)

My only guess is that I'm breaking something by attaching code directly to the onchange event, but I'm at a loss as to the "right" way to hook into that event chain.


If you're willing to use JQuery, it's very simple to do:

http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/


Calling submit() on a form will ignore any submit event handlers, as seen here. You can either

  1. call the event handler directly, or
  2. call click() on the submit button for the form.

The former works best if you use onsubmit and return false instead of using the event argument to the callback, because otherwise you need to pass another messy object or something.

0

精彩评论

暂无评论...
验证码 换一张
取 消