1

I'm trying to make a row in a gridview clickable, so that it causes a postback so that I can then execute code-behind.

I have this in my GridView's RowDataBound event handler. This WORKS:

if (e.Row.RowType == DataControlRowType.DataRow)
{
     e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
     e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
     e.Row.Attributes["onclick"] = "javascript:__doPostBack('PostBackFromItemWindow', '');";
}

But this DOESN'T WORK:

if (e.Row.RowType == DataControlRowType.DataRow)
{
     e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
     e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
     e.Row.Attributes["onclick"] = "<script type='text/javascript'>__doPostBack('PostBackFromItemWindow', '');</script>";
}

Questions:

  1. Why does the first work, but the second doesn't?
  2. In trying to accomplish this task (call code-behind from javascript), are there any alternative methods of doing this? I did some reading and came across WebMethods(), but ultimately didn't like the fact that they need to be static in order to work. The above actually gives me exactly the functionality I need, I just want to make sure that it's an acceptable way of doing it (i.e. it's not deprecated or something), and that I'm not inevitably causing myself trouble later thanks to some unforeseen mistake at this point.
4

1 回答 1

1

This could help you out:

  1. The first one works because, you have specified that the onClick handler is associated to the __doPostBack function which is in javascript. The 'javascript:' just specifies that the function is written in javascript and this should be used only when the script differs from that specified in the meta tag.

    The second one does not work because you have specified the html scripts for the javascript handler. When this goes to the javascript interpreter, it wouldnt be able to understand the tags and hence wouldnt work.

  2. __doPostBack is not recommended for all the cases as mentioned here. But if you have no other choice of creating a postback, then you can use it. This link will be able to give you more info.

于 2012-04-17T15:25:57.240 回答