开发者

javascript OO question - specify private member function in c# object?

I'm not sure how to achieve the following in javascrip开发者_Python百科t, or even if I'm thinking about it correctly. Basically I want to attach a javascript member function to each custom object rendered, so I could have something like this in C#:

public class NumericTextBox : TextBox
{
    ...
    string clientScript = "function isValid() { return isNumericValue(this.value); }"; 
    AttachValidationFunction(clientScript);
}

public class EmailTextBox : TextBox
{
    ...
    string clientScript = "function isValid() { return isEmail(this.value); }"; 
    AttachValidationFunction(clientScript);
} 

and then use the following javascript function in the page

function isFormValid() {
    var controls = getElementsByClass("validatingControl");
    ...
    if (!controls[i].isValid()) return false;
    ...
}

obvisouly in pseudo-code, but hopefully that gives the idea of what I need to achieve. Any suggestions?


what i would do, is to make sure that AttachValidationFunction receives this.ClientID along with the validation function, adds to a list (say, Dictionary<String, String>) and at render time, registers a javascript block with an array of all the added controls, where the result would look like this:

<script type="text/javascript">
var controlsToValidate = [
   { id: 'ctl00_txtNumeric', validate: function(e) { return isNumeric(e.value); } },
   { id: 'ctl00_txtEmail', validate: function(e) { return isEmail(e.value); } }
];
</script>

And then you could iterate over that array like so:

<script type="text/javascript">
function isFormValid() {
   for(var i = 0; i < controlsToValidate.length; i++) {
      var control = controlsToValidate[i];
      var field = document.getElementById(control.id);

      if(!control.validate(field))
         return false;
   }

   return true;
}
</script>

I hope that's quite clear.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜