Using code nuggets for setting controls properties - asp.net

Why cant i use code nuggets to set a control property??For example a validationgroup of a button or the text property of a label.
<asp:Button ID="btn" runat="server" Text="test" ValidationGroup='<% =TestValidate %>'
<asp:Label ID="lbl" runat="server" Text='<% =Test %>' />
Is there any way to set a controls properties without using codebehind?

You could use data binding:
<asp:Label ID="lbl" runat="server" Text='<%# "Hello World" %>' />
provided that you call DataBind in code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataBind();
}
}

<%=SomeVar %> uses late binding which behaves like a Response.Write (in Page.PreRender, if I remember correctly). Hence it will not be utilized by the server controls like the way you wanted it. Unless you use code-behind or inline-code-behind to perform binding.

Related

How to set CSS class to Button control using Session value in design page

I want to set CSS class to asp:Button control using Session value. I have tried this, but it does not works.
<asp:Button ID="btnSave" runat="server" Text="<%$ Resources:Application,Save %>" CssClass="<%# Common.SessionInfo.Button %>" ValidationGroup="save"
OnClick="btnSave_Click" />
It works fine, when I set it from code behind
btnSave.CssClass = Common.SessionInfo.Button;
Please help...
You need to call DataBind method from code behind as in code below. When you use expression like <%# %> then you need to call databind on that server control in your code-behind.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.btnSave.DataBind();
}
}
You may create method in your code behind:
public string GetButtonClass(){
return Session["your_key"].ToString();
}
and call this method to your button:
<asp:Button ID="btnSave" runat="server" Text="<%$ Resources:Application,Save %>" CssClass="<%=GetButtonClass()%>" ValidationGroup="save"
OnClick="btnSave_Click" />

Passing CommandArguement to LinkButton from variable

I have seen many resources on SO that say that I can use following syntax to pass value to CommandArguement of `LinkButton'
<%forearch(var comment in Comments){%>
<asp:LinkButton ID="del" CommandArguement='<%= comment.CommentId%>' onCommand="delete_click" Text="Delete"/>
<%}%>
But when I write this in my ascx file and click on the link the value passed to command argument is "<%=comment.CommentId%>" instead of commentId itself. Please guide what am I doing wrong?
Edit 1
based on answers and comments, I have moved to use repeater instead of foreach and plain code. Here is the code I have come up with
<asp:Repeater ID="commRepeater" SelectMethod="GetPageComments" runat="server">
<ItemTemplate>
<p>
<%#Eval("Comment") %>
<%if(Page.User.Identity.IsAuthenticated && Page.User.Identity.GetUserId() == Eval("UserId")){ %>
<span>
<asp:LinkButton Text="Edit" runat="server" ID="EditLink" CommandArgument='<%#Eval("CommentId")%>' OnClick="Update_Comment" />
<asp:LinkButton Text="Delete" runat="server" ID="DeleteLink" CommandArgument='<%#Eval("CommentId")%>' OnClientClick="if (!confirm('Are you sure you want delete?')) return false;" OnCommand="Delete_Comment" />
</span>
<%} %>
</p>
</ItemTemplate> </asp:Repeater>
you can see that I am trying to show the edit and delete links if user is logged in and his Id matches with user who commented but it tells me that I can on use Eval in databound controls. how would I hide/show edit/delete links conditionally within repeater
You could simply use codebehind, for example in Page_Load:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
del.CommandArgument = comment.CommentId;
}
}
Maybe a better approach would be to use the Comments-collection(which seems to be a list or array of a custom class) as DataSource of a Repeater(or other web-databound control). Then you can add the LinkButtons to the Itemtemplate.
You can then either use ItemCreated or ItemDataBound events of the repeater in codebehind or inline ASP.NET tags to bind the CommandArgument.
For example:
CommandArguement='<%# DataBinder.Eval( Container.DataItem, "CommentId" ) %>'
What you are doing currently is not recommended and is highly error prone. You can easily achieve this with ASP.NET Repeater control like this:-
<asp:Repeater ID="MyRepeater" runat="server">
<ItemTemplate>
<asp:LinkButton ID="del" CommandArguement='<%# Eval("CommentId") %>'
OnCommand="del_Command" Text="Delete" runat="server" />
</ItemTemplate>
</asp:Repeater>
In Page_Load simply bind it:-
if (!Page.IsPostBack)
{
MyRepeater.DataSource = CommentsRepository();
MyRepeater.DataBind();
}
Or Else if you are have ASP.NET 4.5 then use strongly type Data Bound controls like this:-
<asp:Repeater ID="MyRepeater" runat="server" ItemType="MyNamespace.Comment"
SelectMethod="MyRepeater_GetData">
<ItemTemplate>
<asp:LinkButton ID="del" CommandArguement='<%# Item.CommentId %>'
OnCommand="del_Command" Text="Delete" runat="server" />
</ItemTemplate>
</asp:Repeater>
And you method in code behind should be something like this(just for Demo):-
public IEnumerable<MyNamespace.Comment> MyRepeater_GetData()
{
return new List<Comment>
{
new Comment { CommentId =1, Name= "foo"},
new Comment { CommentId =2, Name= "bar"},
};
}

How to set a asp:DropDownList SelectedValue to a Session Variable?

There are several articles describing how to do this is code behind however:
Is it possible to set the value of a dropdownlist to a session variable on the aspx page?
I am using SqlDataSource to populate the dropdownlist so do not wish to add code behind if it can be avoided.
<asp:DropDownList ID="ddl" runat="Server" DataSourceID="sqlDS" DataValueField="ID" DataTextField="TEXT" AppendDataBoundItems="true">
<asp:ListItem Text="" Value="" Selected="True" />
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDS" runat="Server" SelectCommand="spDS" SelectCommandType="StoredProcedure" />
Set Session("ID") as selected value on load?
The dropdown list is already populated from the sqldatasource. I just want to set the initial value on page load.
You need a server side code in order to use Session. The following code doesn't requires code behind file, but again the code inside script will run at server side.
<asp:DropDownList ID="ddl" runat="Server"
DataSourceID="sqlDS"
DataValueField="ID"
DataTextField="TEXT"
AppendDataBoundItems="true"
OnSelectedIndexChanged="ddl_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem Text="" Value="" Selected="True" />
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDS" runat="Server"
SelectCommand="spDS" SelectCommandType="StoredProcedure" />
<script runat="server">
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Session["SelecteValue"] = ddl.SelectedValue;
}
</script>
Note: Make sure AutoPostBack="True" for DropDownList.
Do not mix code with markup. It makes sense to separate them for many reasons. So ASPX will have just the presentation, and CS/VB just the code logic.
When you compile/deploy your side to production - there will not be "the second page" - only ASPX page will remain. Code will be compiled into a DLL.
you'll need an event for your dropdown list on change. Are you using C# or VB.net for your codebehind?
add to onSelectedIndexChanged="ddl_OnSelectedIndexChanged"
to your code behind add:
{this is C# vb is similar}
protected void ddl_OnSelectedIndexChanged(Object sender, EventArgs e)
{
Session["selectedID"] = ddl.selectedValue;
}
to your page load, add
if (isPostback)
{
ddl.selectedValue = Session["selectedID"];
}

ASP.NET Textbox AutoPostBack Not Firing

After searching I've found a number of suggestions, but none of them are fixing the issue.
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text=""></asp:TextBox>
In the properties window, EnableViewState = True for the TextBox (Suggested here). I am typing a new value into the TextBox and then hitting the Tab key. Nothing happens nor does the break point at if(IsPostBack...) break.
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && uid.Text != "" && pw.Text == "")
{
Do stuff
}
}
UPDATE: Other TextBox setups I've tried:
<asp:TextBox runat="server" ID="uid" Text="" AutoPostBack="True" OnTextChanged="UidTextChanged"></asp:TextBox>
protected void UidTextChanged(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('it works');", true);
}
And
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text="" onblur="__doPostBack('','');" OnTextChanged="UidTextChanged"></asp:TextBox>
And
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text="" onblur="__doPostBack('','');"></asp:TextBox>
Whenever AutoPostBack is set to true, I receive the following error in the browser console:
"Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function
__doPostBack
(anonymous function)"
When I have the onblur property set, I receive the exact same error except instead of anonymous function it says onblur.
You could add a javascript event to the onblur for it. onblur='__doPostBack('','');'
That would cause your text box to cause a postback once it is tabbed out of.
Edit: It should be " not ' <asp:TextBox ID="TextBox1" runat="server" onblur="__doPostBack('','');" /> Just tried that and it works. Try removing the AutoPostBack="True"
Edit 2: Base on your pastebin....
<asp:Button runat="server" UseSubmitBehavior="True" ID="submit" Text="Save"
onclick="SubmitClick"/>
You can't have an ID of "submit". Change that to "btnSubmit" and the Javascript solution will work and I bet the Auopostback solution will too.
http://www.xpertdeveloper.com/2012/05/property-submit-of-object-is-not-a-function/ will explain the problem.
You can add OnTextChanged="TextBox1_TextChanged" on your textBox
Nota : It's important to set event fire, no just AutoPostBack="true".
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text="" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
Code Behind:
protected void TextBox1_TextChanged(object sender, System.EventArgs e) {
.....
}

How to use ASP.NET <%= tags in server control attributes?

This works:
<span value="<%= this.Text %>" />
This doesn't work:
<asp:Label Text="<%= this.Text %>" runat="server" />
Why is that?
How can I make the second case work properly, i.e., set the label's text to the value of the "Text" variable?
Use Data binding expressions
<asp:Label ID="Label1" runat="server" Text="<%# DateTime.Now %>" ></asp:Label>
Code behind,
protected void Page_Load(object sender, EventArgs e){
DataBind();
}
you can do this
<asp:Label ID="Label1" runat="server" ><%= variable%></asp:Label>
You will need to set the value of the server control in code
First of all, assign an ID to the label control so you can access the control
<asp:Label ID="myLabel" runat="server" />
Then, in your Page_Load function, set the value of your labels 'Text' field
protected void Page_Load(object sender, EventArgs e)
{
myLabel.Text = 'Whatever you want the label to display';
}
This function will be in your code behind file, or, if you are not using the code behind model, inside your aspx page you will need
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
myLabel.Text = 'Whatever you want the label to display';
}
</script>
Good luck.
In my code i am using something like this easily but in the databound control like ListView Item template
<asp:HyperLink ID="EditAction" class="actionLinks" Visible='<%#Eval("IsTrue").ToString() != "True"%>' runat="server" NavigateUrl='<%# Eval("ContentId","/articles/edit.aspx?articleid={0}")%>' />
But when i tried to use outside the databound control using <%# .. %>, it simply doesn't work.
You can easily do with
My href
But for server controls, and outside of databound control. We need to call DataBind() in pageload event explicitly
<asp:Hyperlink ID="aa" NavigateUrl='<%#myHref%>' >
Not sure how to mark this as such, but this is a bit of a duplicate. See this thread.
I don't think embedding code in to your markup will really make your markup any clearer or more elegant.
<asp:Label> is compiling at runtime and converting to html tags. You can set text with codebehind or like this:
<asp:Label id="Text1" runat="server" />
<% Text1.Text = this.Text;%>
UPD: Seems like my variant doesnt work, this is better:
protected void Page_Load(object sender,EventArgs e)
{
Text1.Text = this.Text;
}
Just pitching this little nugget in for those who want a good technical breakdown of the issue -- https://blogs.msdn.microsoft.com/dancre/2007/02/13/the-difference-between-and-in-asp-net/
I think the crux is in pretty decent agreement with the other answers:
The <%= expressions are evaluated at render time
The <%# expressions are evaluated at DataBind() time and are not evaluated at all if DataBind() is not called.
<%# expressions can be used as properties in server-side controls. <%= expressions cannot.

Resources