html - detecting value change of a hidden field using Razor, then calling the JavaScript function onchange event -


how change value of hidden field using razor, , call javascript function alert("hello") onchange event.

for reason code below not working...

<input id="trigger" name="trigger" type="hidden"  value="6" onchange="alert("hello") />  @{    var hiddenfieldvalue = @html.hidden("trigger", "5"); // better retrieve value @ first 6, rather assigning 5.   // code below should cause hidden field value change, call alert("hello")      if(hiddenfieldvalue.tostring() == "2")         @html.hidden("value","3");     else         @html.hidden("value", "2");   }   <!doctype html>  <html lang="en">  <head>    <title>add numbers</title>    <meta charset="utf-8" />    <style type="text/css">      body {background-color: beige; font-family: verdana, arial;         margin: 50px; }      form {padding: 10px; border-style: solid; width: 250px;}    </style>  </head> <body> </body> </html> 

you seem have several misunderstandings here.

firstly, razor code runs completion serverside, , final rendered page delivered browser runs javascript code - there no interaction between 2 other whatever parts of javascript razor code outputs.

also html.hidden() writes out html hidden form field - @ no point it's .tostring() evaluate value. also, if prefixed @ outputs @ point have line, code output html hidden field name value , value 2 before doctype line, due if never matching , being positioned before doctype. want move inside non-existant <form> tag although i'd recommend using @using (html.beginform()) { ... } generate , putting code dealing hidden field within that.

if wish detect change in razor, can use check surround output of javascript code fire alert(). either there no change code never part of rendered page, or there change , code output, , run once page gets browser (assuming client hasn't disabled javascript).


Comments