views:

493

answers:

3

I got a problem with a button control in asp.net webforms.

After using mvc a bit i started using foreach in the aspx files in webforms too, instead of repeaters, mostly cause of all the junk viewstate a repeater creates.

It works great when you just iterate over html controls. But i got a hard time with button controls.

<% foreach (var r in Reports) { %>
    <asp:LinkButton OnClick="Click_DeleteResult" CommandArgument='<%= r.ResultId.ToString() %>' runat="server">Delete</asp:LinkButton>
<% } %>

On postback the commandargument on that button becomes "<%= r.ResultId.ToString() %>". So that code doesn't get executed. Is there a good way to fill control properties this way?

A: 

Have you tried a DataBinding expression

<%# r.ResultId %>
Steve
A: 

How about adding it via code behind, this is a quick and dirty example but I think you get the idea:

HtmlTable table = new HtmlTable();
foreach (var r in Reports)
{
    LinkButton lnkbtn = new LinkButton();
    lnkbtn.CommandArgument = r.ResultId;
    lnkbtn.Click += Click_DeleteResult;
    HtmlTableRow tr = new HtmlTableRow();
    HtmlTableCell tc_resultID = new HtmlTableCell();
    tc_caseNo.Controls.Add(lnkbtn);
    tr.Cells.Add(tc_resultID);
    table.Rows.Add(tr);
}
div_yourContainerDiv.Controls.Add(table);

I sometimes prefer this solution.. depends on the assignment.. However there's probably a solution for your current issue that doesn't require you to take it to code behind :)

If you work a lot with generic content it can be a quite nice way to do it without any viewstate bullshit code fucking everything up for the SE's.

Alternate you could do something I have done with success with some SEO critical projects. You can take and save the viewstate as a session and create a Session key to the viewstate instead. That way you let the server handle the viewstate rather than the client. It creates additional serverload but there will always be tradeoffs.

The real napster
A: 

This is ugly. The #1 benefit of using ASP.NET (especially MVC) is separating the logic and presentation. I cringe every time I have to look in an aspx file for executing code.

If you don't like the ViewState "junk" then just turn it off for that control!

<asp:Repeater ID="MyRepeater" runat="server" EnableViewState="false">

If you insist on this though... I've seen situations like this where ASP.NET would not parse a server tag correctly unless I dropped the surrounding quotes. Like so:

CommandArgument=<%= r.ResultId.ToString() %>

Might not be completely conforming HTML, but ASP.NET doesn't care. If you really need to output those surrounding quotes for some reason you can put them inside the server tag instead of outside. It's counter-intuitive, but sometimes you have to do it that way.

Bryan