简体   繁体   English

如何为HTML助手ASP.NET MVC编写Javascript代码?

[英]How to write Javascript code for HTML helpers ASP.NET MVC?

I have an HTML helper textBox like this: 我有一个HTML帮助器文本框,如下所示:

@Html.TextBox("txt1") <br />

Now I want to fire a javascript onchange event on this textbox. 现在,我想在此文本框上触发javascript onchange事件。 Is it possible to do so or should I use an HTML input type instead. 是否可以这样做,还是应该改用HTML输入类型?

You can specify html attributes using the htmlAttributes parameter of the TextBox Html helper method like so: 您可以使用TextBox Html帮助器方法的htmlAttributes参数指定html属性,如下所示:

@Html.TextBox("txt1", null, new { onchange="..." })

See: InputExtensions.TextBox Method 请参阅: InputExtensions.TextBox方法

From the above link: 从上面的链接:

The htmlAttributes parameter consists of an object that contains name/value pairs. htmlAttributes参数由一个包含名称/值对的对象组成。 The attributes that are specified in the name/value pairs depend on the HTML element that is being rendered. 名称/值对中指定的属性取决于正在呈现的HTML元素。

If you have an ID for this textbox, you can hook the event to the textbox using Jquery. 如果您有此文本框的ID,则可以使用Jquery将事件挂接到文本框。

$("#textboxid").keydown(function(event) {
    alert("Hey!");
});

Note that I've used the Keydown event. 请注意,我已经使用了Keydown事件。 You can also use press or up events. 您还可以使用新闻或向上事件。

Or you can make the binding in the ready event. 或者,您可以在ready事件中进行绑定。

$(document).ready(function(){
        $("#textboxid").bind("onchange", yourfunction);
          });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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