Accessing web config value from asp:ListItem - asp.net

I'm trying to print the value I have stored in the web config as text for a list item.
<asp:ListItem Enabled="true" Selected="true" Text="Web Only - <%$ AppSettings:SubscriptionPrice %>"
Value="web" />
will give me: Web Only - <%$ AppSettings:SubscriptionPrice %>
However, if I remove the Web Only text and do this:
<asp:ListItem Enabled="true" Selected="true" Text="<%$ AppSettings:SubscriptionPrice %>"
Value="web" />
I'll get the variable desired. Is there a way to have the text and the value from my appsettings?

You cannot do it inline that easily. Your options are:
Set the complete value in your AppSettings. (easy)
Set the value from code behind. (easy)
Lastly, if you want to be in ASPX and nothing else is acceptable, you need to write a CodeExpressionBuilder so that you can provide custom code, as follows: (may be an overkill)
here is the code expression builder
namespace Funky
{
[System.Web.Compilation.ExpressionPrefix("Code")]
public class CodeExpressionBuilder : System.Web.Compilation.ExpressionBuilder
{
public override System.CodeDom.CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, System.Web.Compilation.ExpressionBuilderContext context)
{
return new System.CodeDom.CodeSnippetExpression(entry.Expression);
}
}
}
add this web.config entry
<compilation debug="true" targetFramework="4.5">
<expressionBuilders>
<add expressionPrefix="MyCode" type="Funky.CodeExpressionBuilder"/>
</expressionBuilders>
</compilation>
finally use the code expression as follows:
<asp:ListItem Enabled="true" Selected="true" Text='<%$ MyCode: "Web Only - " + ConfigurationManager.AppSettings["SubscriptionPrice"] %>' Value="web" />

I'm not sure you can do this on page, but you can do this in your code file:
ListItem item = new ListItem();
item.Text = "Web Only - " + System.Configuration.ConfigurationManager.AppSettings["SubscriptionPrice"];
item.Value = "web";
item.Selected = true;
ListBox1.Items.Add(item);

Sorry about the earlier post.
I think you are going to have to bind the value is code.
ddl.Items.Clear()
ddl.Items.Add(New ListItem("Web Only -" & ConfigurationManager.AppSettings("SubscriptionPrice"), "Web"))

Related

Add HTML5 placeholder text to a textbox .net

I have a standard input:
<asp:TextBox type="text" runat="server" id="txtSearchTerm" />
I'd like to have this render with a dynamic HTML5 placeholder. Something like:
'Code Behind
txtSearchTerm.**placeholder** = "Search " + Site.Name
So that it outputs the following HTML:
<input type="text" runat="server" id="txtSearchTerm"
placeholder="Search Site #1" />
where Site.Name = "Site #1".
txtSearchTerm.placeholder is not a property. I have it set to text and then run javascript to show/hide on focus BUT I would much rather just use the HTML5 placeholder value. How can I render this?
Please no JS/client side solutions.
You could use the Attributes collection. So you would have something like
txtSearchTerm.Attributes.Add("placeholder", "Search" + Site.Name);
or
txtSearchTerm.Attributes["placeholder"] = "Search" + Site.Name; // or Attributes("placeholder") if you're using vb.net
And if you're using resources for localization/translation:
txtSearchTerm.Attributes["placeholder"] = GetLocalResourceObject("YourLocalResourceName").ToString();
Because I find it annoying/tiresome to add all the placeholders from the code behind. You can create a new TextBox Class that inherits the WebControls TextBox and then you can add the placeholder from the CodeBehind or from the HTML Side.
TextBox.cs (Placed in Project/Controls/)
namespace Project.Controls
{
public class TextBox : System.Web.UI.WebControls.TextBox
{
public string PlaceHolder { get; set; }
protected override void OnLoad(EventArgs e)
{
if(!string.IsNullOrWhiteSpace(PlaceHolder))
this.Attributes.Add("placeholder", PlaceHolder);
base.OnLoad(e);
}
}
}
Register Control In the Web.Config:
<system.web>
<pages>
<controls>
<add tagPrefix="ext" assembly="Project" namespace="Project.Controls" />
</controls>
</pages>
</system.web>
(use whatever tag prefix you want)
Usage:
<ext:TextBox runat="server" id="SomeId" PlaceHolder="This is a PlaceHolder" />
or from the code behind
SomeId.PlaceHolder="This is a PlaceHolder";
I just put placeholder property in HTML code and works:
<asp:TextBox placeholder="hola mundo" ID="some_id" runat="server"/>
There is also the TextBoxWatermark extender included in Microsoft's Ajax Control toolkit. It's not HTML5, but it's backwards compatible (I believe).
http://www.asp.net/AjaxLibrary/AjaxControlToolkitSampleSite/TextBoxWatermark/TextBoxWatermark.aspx
<ajaxToolkit:TextBoxWatermarkExtender ID="TBWE2" runat="server"
TargetControlID="TextBox1"
WatermarkText="Type First Name Here"
WatermarkCssClass="watermarked" />

Set TemplateField HeaderText dynamic for localization

I am trying to create localization for my ASP.NET code, but I have issues setting the TemplateField's HeaderText
I have this that works
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<%# Eval("Description") %>
</ItemTemplate>
<FooterTemplate>
<asp:Panel ID="Panel5" runat="server" DefaultButton="EditSubmission">
<asp:TextBox runat="server" ID="Submission_DescriptionTxtBox" TextMode="MultiLine"
ToolTip='<%# GetById("atforbedringsforslag_description_tooltip") %>'/>
</asp:Panel>
</FooterTemplate>
</asp:TemplateField>
But I want to change
<asp:TemplateField HeaderText="Description">
To
<asp:TemplateField HeaderText='<%# GetById("atforbedringsforslag_description_title") %>'>
But then I get
Databinding expressions are only supported on objects that have a DataBinding event. System.Web.UI.WebControls.TemplateField does not have a DataBinding event.
How should I set this field? I can find some that uses OnRowCreated, but then you access the fields with an index number, and then it becomes easy to make mistakes or forgot to change indexes if new fields are added later on
EDIT My solution:
Created the custom expression builder
using System.Web.Compilation;
using System;
using System.CodeDom;
public class LocalizationExpressionBuilder : ExpressionBuilder
{
public override CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
{
CodeExpression[] inputParams = new CodeExpression[] { new CodePrimitiveExpression(entry.Expression.Trim()),
new CodeTypeOfExpression(entry.DeclaringType),
new CodePrimitiveExpression(entry.PropertyInfo.Name) };
// Return a CodeMethodInvokeExpression that will invoke the GetRequestedValue method using the specified input parameters
return new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(this.GetType()),
"GetRequestedValue",
inputParams);
}
public static object GetRequestedValue(string key, Type targetType, string propertyName)
{
// If we reach here, no type mismatch - return the value
return GetByText(key);
}
//Place holder until database is build
public static string GetByText(string text)
{
return text;
}
}
Added the prefix to my web.config
<system.web>
<compilation debug="true" defaultLanguage="c#" targetFramework="4.0">
<expressionBuilders>
<add expressionPrefix="localizeByText" type ="LocalizationExpressionBuilder"/>
</expressionBuilders>
</compilation>
</system.web>
And I can now get my text like this
<asp:TemplateField HeaderText='<%$ localizeByText:Some text %>'>
You can build your own custom Expression Builder which calls your GetById method. Look at the following link for an old but good article explaining how to build an expression builder and how to use it:
https://web.archive.org/web/20210304125044/https://www.4guysfromrolla.com/articles/022509-1.aspx
When you have an expression builder, you use it with the <%$ syntax. This is different from the databinding syntax <%#.
For the HeaderText field, it is not allowed to use DataBinding syntax (not sure why, but that's how MS made it). Using expression syntax IS allowed and will work once you have your custom expression builder done.
Do go through the page I linked to, it's quite a lot of text, but in the end making you expression builder will not take much effort...
Also, the page has a link at the bottom to a library of expression builder that the author has made. Have a look at them, maybe one of them could be used directly to solve your problem (specifically, the CodeExpressionBuilder).

HTTPContext.Current.User.Identity.Name not working inside a control?

I have a label and I want to set text of this label to
HTTPContext.Current.User.Identity.Name
So I wrote
Text = '<%=HTTPContext.Current.User.Identity.Name %>'
but it doesn't work, however when I wrote this outside of the lable for example:
<h2>
<%=HTTPContext.Current.User.Identity.Name %>
</h2>
it works.
<asp:Label ID="lbUserName"
runat="server"
Text='<%# HttpContext.Current.User.Identity.Name %>'
/>
in Page_Load
if (!Page.IsPostBack )
{
lbUserName.DataBind();
}
use label like this
<asp:label id="lblx" runat="server" ><%= HTTPContext.Current.User.Identity.Name %></asp:label>
To bind the text like this you will have to create your own custom expression builder.
First, add such class to your namespace:
using System.Web.Compilation;
using System.CodeDom;
[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context)
{
return new CodeSnippetExpression(entry.Expression);
}
}
Next step is adding this to your web.config file:
<compilation debug="true">
<expressionBuilders>
<add expressionPrefix="Code" type="YourNameSpace.CodeExpressionBuilder"/>
</expressionBuilders>
</compilation>
Then finally this should work:
<asp:Label id="YourLabel" runat="server" Text='<%$ Code:HttpContext.Current.User.Identity.Name %>' />
Complicated way to achieve something simple, but this will allow you to use the syntax you want throught your whole project so might worth the extra effort.
Reference.

Is it possible to create a generic Util Function to be used in Eval Page

I am currently binding a Nullable bit column to a listview control. When you declare a list view item I need to handle the case when the null value is used instead of just true or false.
<asp:Checkbox ID="Chk1" runat="server"
Checked='<%# HandleNullableBool(Eval("IsUsed")) %>' />
Then in the page I add a HandleNullableBool() function inside the ASPX page.
protected static bool HandleNullableBool(object value)
{
return (value == null) ? false : (bool)value;
}
This works fine but I need to use this in several pages so I tried creating a utility class with a static HandleNullableBool. But using it in the asp page does not work. Is there a way to do this in another class instead of the ASPX page?
<asp:Checkbox ID="Chk1" runat="server"
Checked='<%# Util.HandleNullableBool(Eval("IsUsed")) %>' />
You can simply write
<asp:Checkbox ID="Chk1" runat="server"
Checked='<%# Eval("IsUsed") ?? false %>' />
To answer your question, you need to include the namespace that contains the class, like this: (at the top of the file)
<%# Import Namespace="Your.Namespace.Here" %>
You can also do this in Web.config:
<pages>
<namespaces>
<add namespace="Your.Namespace.Here" />
</namespaces>
</pages>

ASP.NET updatepanel + invalid postback

I have the following very simple form:
<asp:UpdatePanel ID="ClaimRewardsForm" runat="server">
<ContentTemplate>
<span class="largeBold">Select jacket weight:</span><br />
<asp:RadioButtonList runat="server" ID="JacketWeight">
<asp:ListItem Value="Lightweight" Text="Lightweight (fleece)" />
<asp:ListItem value="Heavyweight" Text="Heavyweight (cotton)" />
</asp:RadioButtonList>
<br />
<span class="largeBold">Select size:</span><br />
(Men's sizes only)<br />
<asp:DropDownList ID="JacketSize" runat="server">
<asp:ListItem Value="Small" Text="Small" />
<asp:ListItem Value="Medium" Text="Medium" />
<asp:ListItem Value="Large" Text="Large" />
</asp:DropDownList><br />
<br />
<asp:ImageButton ID="SubmitButton" runat="server" ImageUrl = "~/Content/Images/submitButton.png" onclick="SubmitButton_Click" />
</ContentTemplate>
</asp:UpdatePanel>
In my button's click handler, I have:
protected void SubmitButton_Click(object sender, EventArgs e)
{
if (IsValid)
{
using (var work = UnitOfWorkFactory.Create())
{
var id = new Guid(Session["id"].ToString());
var account = UserAccounts.Get(id);
if (account == null)
throw new Exception("Invalid user account id.");
account.RewardInfo.Clear();
account.RewardInfo.Add(new RewardInfo()
{
UserAccount = account,
JacketWeight = JacketWeight.SelectedValue,
JacketSize = JacketSize.SelectedValue
});
work.Commit();
}
//ClaimRewardsForm.Update();
//ScriptManager.RegisterStartupScript(this, GetType(),
// "confirmation", "ClaimRewards.showConfirmation();", true);
}
}
I'm not modifying the form fields in any way whatsoever, but I'm still getting the following error:
505|error|500|Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.|
Since I'm not modifying teh controls at all during the post back, I cannot for the life of me figure out why it's acting as if I had. Any thoughts?
This guy here is your culprit. You'll have to figure out what you are posting to cause it to block the request or disable EventValidation if you understand the security risks.
I don't see anything in your posted code but <> in option values messes with it for sure.
Stupid me. I'm using a DropDownList adapter to allow for optiongroup elements within my list but that was causing an invalid postback because it modifies the elements in the list behind the scenes without registering the modified values for event validation. I modified the adapter to perform the registration and it works fine now.

Resources