简体   繁体   English

注册到剃须刀@ Html.HiddenFor的onchange事件

[英]Registering to onchange event for razor @Html.HiddenFor

I am using asp.net mvc 4, jquery and razor. 我正在使用asp.net mvc 4,jquery和razor。 I have below razor statemet in my view: 我认为剃须刀剃须刀以下:

@Html.HiddenFor(m => m.MyItemViewModel.id);

I need to call a jquery/javascript function when its value changes. 当其值更改时,我需要调用jquery / javascript函数。 So I have thought to suscribe jquery/javascript function to onchange event for HiddenFor razor tag but I do not know if it is possible. 因此,我曾考虑将jquery / javascript函数订阅到HiddenFor razor标签的onchange事件,但我不知道这是否可能。

I have implemented below code but it seems to not work as OnHiddenValueChanged is not reached: 我已经实现了以下代码,但由于未达到OnHiddenValueChanged,因此似乎无法使用:

@Html.HiddenFor(m => m.ItemCompViewModel.id, new { onchange="OnHiddenValueChanged" });

<script>
    function OnHiddenValueChanged() {
    }
</script>

Or even better, how to detect from view when m.ItemCompViewModel.id (the item for my view model) has changed and then call the jquery/javascript function? 甚至更好的是,如何在m.ItemCompViewModel.id(我的视图模型的项目)已更改时从视图中进行检测,然后调用jquery / javascript函数?

Any ideas? 有任何想法吗?

It looks like you are attempting to subscribe to the onchange client side function for a value that is generated on the server and changes only on the server. 似乎您正在尝试订阅onchange客户端功能以获取在服务器上生成且仅在服务器上更改的值。 So it's normal that this client side function is never triggered. 因此,通常不会触发此客户端功能。 Actually you never used any javascript to change the value of the hidden field so you cannot expect this callback to be raised. 实际上,您从未使用过任何JavaScript来更改隐藏字段的值,因此您不能期望会引发此回调。

If you are modifying the value on the server, then it's up to the server to tell the client that the value changed. 如果您要修改服务器上的值,则由服务器来告知客户端该值已更改。 For example you could have some additional property on your view model telling that the value has changed (whatever that means in your context - because changed .must always be compared to some previous state). 例如,您可以在视图模型上具有一些附加属性,以告知值已更改(在上下文中意味着什么-因为更改后的。必须始终与以前的状态进行比较)。 Then on the client you could serialize this property as a javascript variable so that the client side knows about the change that occured on the server. 然后在客户端上,您可以将该属性序列化为javascript变量,以便客户端知道服务器上发生的更改。

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

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