简体   繁体   中英

asp.net mvc: difference between dropdown & textbox onchange event

Having some pain with this event, I have some code like this for a dropdown:

return helper.DropDownList(data.ModelEntityId.ToString(), selectList, "<Select>", new { onChange = onChange });

where onChange is a variable containing a javascript function to run, this works great. However with the textbox version (below) the onchange event is fired when the page loads (unlike the DropdownList, different behavior is annoying). When the javascript function is called at the time the page is loading I get the error: Javascript "undefined" could not be found... (it then works subsequently)

return helper.TextBox(data.ModelEntity.ModelEntityId.ToString(), data.ValueText, new { onchange = onChange });

Example javascript

function SuitabilityChecked(providerId, checkId, parentId) {
            alert("meep"); // just to test error still occurs
        };

Is there a different event I should use for a textbox, or something "special I need to do?

You could avoid this problem entirely by applying your handlers unobtrusively (not inline) after the page load is complete. The standard way to do this in MVC is with jQuery.

 <script type="text/javascript">
    $(function() {
         $('input#<%= data.ModelEntity.ModelEntityId %>').change( function() {
              ...
         });
    });
 </script>

Using classes would make it even easier to apply the handlers to only certain elements, if desired -- just add the class definition to the htmlAttributes hash in the helper and change the selector in the onloaded handler to apply the change handler to only those elements with the selected class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM