开发者

Call Javascript from Button inside ASP Repeater?

I'm using an ASP Repeater. In the <ItemTemplate> and the <AlternatingItemTemplate> there are, among other labels, etc, 3 HTML buttons (<input type="button"...) that make different javascript/jquery calls when clicked. This is working fine.

Now, I want to dynamically show/hide these buttons based on a boolean that is bound to my Repeater. I know if I were using an ASP Button, that I could simply use something like:

Vi开发者_运维问答sible='<%# Eval(bMyBoolean) %>'

I tried switching my HTML buttons to ASP Buttons but then I couldn't get the javascript calls to work correctly. I know you can wire up the Javascript calls in the code behind for each button (in the Repeater.ItemDataBound event), but I'm not sure how to do that in the code behind with my scenario. Here is an example of one of my HTML buttons:

<input type="button" id="myButton" value="Test" onclick="MyJavascriptFunction(this,'<%# CType(Container.DataItem, myClassObject).FirstName%>');" />

In the above example, I'm passing the FirstName value (which is a property of the class object I'm binding to the repeater) to my Javascript function.

To me, it seems like if I'm using an ASP Repeater, then it would make sense to use ASP Buttons, but I don't know if it really makes a difference?

So, my question is: How can I either dynamically show/hide an HTML Button inside an ASP Repeater based on a boolean value that is bound to the repeater? Or, if that is a bad practice, how can I make a javascript call with an ASP Button, like the call above (referencing a value from the Repeater)?

Thanks in advance for any help/advice!


you can dynamically output style information based on your boolean. Consider this:

<itemTemplate>
    <input type='button' style='<%# getVisbility(Eval("MyBoolValue")) %>' 
           value='click me' />
</itemTemplate>

Then in your code, you'd have:

protected function getVisibility(isVisible as boolean) as string 
   if isVisible then
     return "display:inline; "
   else
     return "display:none;"
   end if 
end function 

Now, if you wanted to perform a JavaScript call from the asp.net control, you have options as well:

The simplest -- but by no means best option, is to do inline JS:

<itemTemplate>
   <asp:button runat="server" onclientClick="return confirm('click to submit');" 
               text="Click!" />
</itemTemplate>

there are more complex options with the use of JQuery that would allow you to dynamically capture a click event, and determine the exact row of the repeater that you're selecting for. One example of this is:

<itemTemplate>
   <asp:button cssclass ='clickMe' runat="server" rel='<%# Eval("MyCol")%>' 
               text="Click!" />
</itemTemplate>

Then the jquery code:

$(".clickMe").click(function(){
  var myVal = $(this).attr("rel");
})
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜