简体   繁体   中英

Write asp.net tag in javascript block

This is my code :

$(document).ready(function () {
var url = '<%: Url.Content("~/") %>' + "Home/Gallery";
$.getJSON(url, function (newProduct) {
    var contentNewProduct = $("ul.ei-slider-large");
    var smallNewProduct = $("ul.ei-slider-thumbs");
    $.each(newProduct.ja, function (index, data) {
        contentNewProduct.append('<li><img src="' + '<%:Web.HelperClasses.HelperClass.CheckImageUrlExist("' + data.PictureName10 + '")%>' + '" alt="image" /><div class="ei-title"><span class="productName">' + data.Name + '</span><span class="productPrice">' + data.Price + '</span><span class="productSpec"><br /><br />"' + '<%:Web.HelperClasses.HelperClass.TrimString(' + data.Notes + ',2)%>' + '"</span><span><a href="#" class="readmore">Read more...</a></span>' + '</div></li>');
    });
});
});

The error block '<%:Web.HelperClasses.HelperClass.TrimString(' + data.Notes + ',2)%>' , the error is Too many characters in character literal .

This is the form of function : TrimString(string s,int total) .

I tried to change to '<%:Web.HelperClasses.HelperClass.TrimString("' + data.Notes + '",2)%>' , but it still didn't work.

This is the c# TrimString function :

public static string TrimString(string str, int lenght)
{
string _str = str;
int _iAdditionalLenght = 0;
for (int i = lenght; i < str.Length; i++)
{
    if (_str.Substring(i, 1) == " ")
        break;
    _iAdditionalLenght++;
}
return str.Substring(0, str.Length < (lenght + _iAdditionalLenght) ? str.Length : (lenght + _iAdditionalLenght));
 }

This is what I tried in javascript,but it didn't work :

function TrimString(str, lengthStr) { 
  var _str = str;
  var _iAdditionalLenght = 0;
  for (var i = lengthStr; i < str.length; i++)
  {
      if (_str.substring(i, 1) == " ")
        break;  
      _iAdditionalLenght++;
  }

  return str.substring(0, str.length < (lengthStr + _iAdditionalLenght) ? str.length : (lengthStr + _iAdditionalLenght));
 }

Could any one tell me how can I write this function of TrimString in my block of javascript?

Thanks you so much.

If I guess right what your doing, you just can't. js is executed in client side, while aspnet is executed in server side. You can't create aspnet tags using js, because they need to be compiled and executed in server side.

If you just need a trim function, why not use jquery's built in trim function?

http://api.jquery.com/jQuery.trim/

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