Restrict the text length assigned for Link Button from DB - c#

I have some text being fetched from the DB, which I am binding to the DataList ItemTemplate in the following form:
<asp:LinkButton runat="server" Text='<%#Eval("url")%>' />
The text that is fetched from the DB might be long and I want to restrict it to (let's say 50 chars at max. with a ... afterwards) in the above eval assignment.
How can this be done here?
Secondly, how do I specify the link here in LinkButton so that on clicking on it, it goes to the specified, the link should open in a new window as in taget=_blank

You can use a tag directly
<a href='<%#Eval("url")%>' taget=_blank> <%# BindText(Eval("url"))%></a>
Codebehind:
public string BindText(obj url)
{
if(url!=null) {return (url.ToString().length > 50) ? url.ToString().Substring(0,50) + '...': url.ToString() ;}
return "";
}

One easy way to handle that would be to create a "Truncate" extension of type String which simply strips X characters from the end of it.
Regarding "target=_blank" - you should be able to accomplish this with the Attributes property of the LinkButton.

Depending on the target browser, using CSS text-overflow is an elegant way to do this at the client instead of the server (maximizes space; only that text which must be truncated will be truncated, and it also takes into account simple punctuation rules).
https://developer.mozilla.org/en/CSS/text-overflow
This blog post shows a decent solution in that it seeks whitespace in which to inject the ellipses (rather than blind truncation).
For setting the target of a LinkButton...
<asp:LinkButton runat="server" target="_blank">
ASP.Net will (usually) ignore attributes that it doesn't recognize and just render them to the client verbatim. However, this won't actually work because a LinkButton is meant to initiate a postback. You can use an anchor tag instead.

Related

ASP.net Web Forms - TextBox displaying wrong encoded text

I am stuck on this problem for a while now.
I did some searches on this and other sites, where the problems got solved, but sadly none worked for me.
Problem:
I develope an asp.net web forms application, for a list of reservations.
The name and prename data values can have german symbols in it (ä, ö, ü, ß).
Basically everything worked fine until I added an edit page for the reservations.
When I set the text of a textbox based on the data values, they text shows ö for ö, ä for ä, ü for ü and ß for ß.
The point is that this only happens in the asp:Textbox.Text, if I use it in a asp:Label.Text it shows the correct name.
So now the question is: Anyone else had this problem and if yes how did you fix it? If not, do you have any ideas how to fix it?
Code + Result Picture
P.S.: Yes everything is utf-8, yes I tried HttpUtility.Decode and such, nothing worked as said at start. In the database it is shown correct too. I can type in an ö without problem, just setting text doesn't work.
EDIT:
After Sonal Borkar's idea, I used a textarea but it is impossible to check a textarea with a RequiredFieldValidator. So now I was messing around in the .net-API and noticed some things:
Only listitem.cs and textbox.cs have this PersistenceMode(PersistenceMode.EncodedInnerDefaultProperty),
set in their text-attribute, things like label.cs have PersistenceMode(PersistenceMode.InnerDefaultProperty).
Also listitem.cs and textbox.cs have an override in their ControlBuilder
public override bool HtmlDecodeLiterals() {
// ListItem text gets rendered as an encoded attribute value.
// At parse time text specified as an attribute gets decoded, and so text specified as a
// literal needs to go through the same process.
return true;
}
Other webcontrols like the label, don't override this method and their method returns false.
BUT still it doens't make any sense, because I have ListItem which has a german symbol in it and it gets rendered perfectly fine. So I am really stuck and confused why no one ever had to mess with this before.
Looking for a solution by myself, but still could use some help.
Edited:
Try below, Good Luck!
1) Use HttpUtility.HtmlDecode
<asp:TextBox ID="EditItem" runat="server" Text="<%#
HttpUtility.HtmlDecode(Item.Name) %>"></asp:TextBox>
2) Set Meta Tag in HTML
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
3) Set Globalization in Web.config
<globalization requestEncoding="utf-8" responseEncoding="utf-8"
fileEncoding="utf-8" />
4) Set the font-family in style of Textbox
<asp:TextBox ID="EditItem" runat="server" Text="<%#
HttpUtility.HtmlDecode(Item.Name) %>" style="font-family: Courier
New;"></asp:TextBox>
5) Replace Textbox with TextArea or RichTextBox
Solution:
After trying around for another few hours, thats the way I made it actually work, if anyone will ever find themselves in the same situation.
In your FormView add an empty TextBox as following:
<asp:TextBox ID="EditName" runat="server" CssClass="form-control" Text=""></asp:TextBox>
In your CodeBehind class, when the page is completely loaded, get your data from the database again, and call a method like this:
protected void GetNameAndPreName()
{
int reservationID = Convert.ToInt32(Request.QueryString["reservationID"].ToString());
ReservationContext _db = new ReservationContext();
Reservation r = _db.Reservations.SingleOrDefault(reservation => reservation.ReservationID == reservationID);
(reservationDetail.FindControl("EditName") as TextBox).Text = r.Name;
(reservationDetail.FindControl("EditPreName") as TextBox).Text = r.PreName;
}
In my case it's name and prename, change to whatever you need. This will the text will be shown correctly.
HINT: This does NOT work for multiline textboxes, as they get encoded everytime as seen in TextBox Source

How to get html control by ID that has hyphens?

I have a front end written in html that I am converting to asp, and many of the controls have names with "-" in them. This is causing crazy headaches, as there is no time to rename everything, and the ctrl-f and replace somehow breaks my css. Is there any way to access these controls in the code behind while they have the dashes? I have tried the code below.
//Can find when there is no dash in it, but that breaks the css after find/replace of full solution
HtmlGenericControl body = (HtmlGenericControl)this.Page.FindControl("page-list");
body.Attributes.Add("class", GlobalVariables.webAppSkin);
//I have also tried this, but logout stays null
WebControl logout = (WebControl)Page.FindControl("logout-link");
This is the html control:
<body id="page-list">
Sorry, that's not gonna happen.
You cannot have an element with an id containing "-", and still be a runat="server" ASP.NET control.
Microsoft's docs about the control's IDs states:
http://msdn.microsoft.com/en-us/library/system.web.ui.control.id.aspx
Only combinations of alphanumeric characters and the underscore character ( _ ) are valid values for this property. Including spaces or other invalid characters will cause an ASP.NET page parser error.
If you tried adding runat="server" to the body tag you showed: <body id="page-list">, it would give you the following line in aspx.designer.cs:
protected global::System.Web.UI.HtmlControls.HtmlGenericControl page-list;
Which is obviously throwing an exception on C# syntax.
<body id="page-list"> is not a HTML Control (i.e. an instance of (a subclass of) System.Web.UI.Control because it doesn't have the runat="server" attribute. If you were to add runat="server" then you would get a JIT compile-time error message informing you that "page-list" is not a valid identifier.
ASP.NET Web Forms 4.0 added the ClientIDMode attribute, however it doesn't allow you to set a completely custom ID attribute value. There's no easy solution for this without using <asp:Literal> or implementing your own control (or my preferred option: switching to ASP.NET MVC).
You can access controls in code behind with their ID if you write runat="server". Here is the example for your case
<body runat="server" id="testID">
In code behind you can access it like this:
body.Attributes.Add("class", value);

Text with RegEx Validator not working

I have an issue with the following text display:
<asp:RegularExpressionValidator ID="Password_RegularExpValidate" runat="server"
Text="TEST!"
Display="Dynamic"
BorderStyle="None"
ControlToValidate="txtNewPass"
ValidationExpression="(?=^.{8,255}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*"
meta:resourcekey="Password_RegularExpValidateResource1" /></td>
The pattern by itself is:
(?=^.{8,255}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*
The text initially had some stuff in it as the ValidationExpression was different. I've changed the regex expression and that works, but when I write something in Text= it doesn't update on the page. I've restarted IIS, cleard the IE chache... everything I could think of. The old text keeps appearings (ie. "TEST!" doesn't show up when the validation fails as it should).
Any help would be appreciated.
Edit:
The code for txtnewpass:
<asp:TextBox ID="txtNewPass" runat="server"
TextMode="Password"
MaxLength="256"
meta:resourcekey="txtNewPassResource1"></asp:TextBox>
Also, it's worth noting that I can remove an entire table from a page that it disappears when I reload the page. But when I change text values from controls or anything that runat="server" and the page doesn't seem to update with the text....
And the code behind doesn't edit the field that displays, the validator validates the text in the textbox and uses that value later.
Edit 2: Same thing happening with -
<asp:Label ID="Label1" runat="server"
Text="Change Password!!!!!"
meta:resourcekey="Label1Resource1"></asp:Label></td>
I've added the exclamation marks (!!!!!) and that's not showing up when I refresh the page either.....
Edit 3: As I've noted in one of the comments, if I delete a table from the page and reload the page, that table disappears, so I know the page is reloading properly. The runat="Server" property, does that work a certain way where it caches text or something? I'm out of ideas....
Like Kirill said, use ErrorMessage instead of Text.
But the main problem is, I think, your localization, which is handled through the meta:resourcekey tag and resources.
Here is a good explanation:
ASP.NET meta:resourcekey
If you set automatically or manually the resource localization file and change something afterwards, for example a Label Text property, then you need to do it in the resource file too. Because there should be your initial value, which is loaded at runtime.
There are a lot of possibilities for the source of the problem, and there's not really enough info to tell which one it is. It sounds to me like one of these:
1) An external issue with your application or page (perhaps your ViewState isn't being set up properly, or the validation is getting called before PostBack).
2) You should be using RegularExpressionValidator.ErrorMessage instead of Text, as Kirill suggested. You said that you had changed that, but I wonder if you've reloaded the page (you could try rebuilding the app or something if it's getting cached somehow).
3) Your regex might not be doing what you think it is. The pattern is extremely long, and it seems strangely written. Adding some whitespace, we find that it looks like this:
(?=^.{8,255}$)
(
(?=.*\d)(?=.*[A-Z])(?=.*[a-z])
|
(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])
|
(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])
|
(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9])
)^.*
Which simplifies down to something like:
^(
(?=.*[A-Z])(?=.*[\W_])(?=.*[a-z\d])
|
(?=.*[a-z])(?=.*\d)(?=.*([A-Z\W_]))
).{8,255}$
Is this what you intended? I see where you're going with the password rules, but it may be easier to just simplify them and require one capital, one lowercase, one number, and one special character. You could also try to get validation working with a simpler regex pattern, and then add complexity once everything else is working.
Try to use RegularExpressionValidator.ErrorMessage instead of Text.
Try restarting VS. Sometimes incredible bugs disappear after that.
Try removing and regenerating your ..aspx.designer.cs file (to
regenerate right click the aspx/ascx file and choose "convert to web
application").
Agree with others, you should indeed check your resource file.

ASP.NET Content page dynamic content comes out at the top of the HTML output

I'm very new to ASP.net. I have a c# content page, in which I want to inset this code half way down within the HTML:
<%
HttpResponse r = Response;
r.Write(HttpContext.Current.Request.ServerVariables["SERVER_NAME"]);
%>
But when I view the page, this content comes out first, before even the tag.
Any ideas on how to get this code inline instead?
Thanks!
EDIT
I'd just like to add a note to all who answered this question to explain what you've done.
You spared your valuable time to help me, a stranger to you, solve a difficult problem at work, which allowed me to get out of the office on Friday night, just in time to catch the last bus to my home 50 miles away, and see my wife who was sick in bed. You didn't just answer my question, you made my day SO much better. THANK YOU so much!
Steven
Because you are doing a Response Write, that will push out before everything else. If you want to just imbed something at a specific point you can do:
<%= HttpContext.Current.Request.ServerVariables["SERVER_NAME"]) %>
This <%= %> will write any string to that exact location in the HTML.
You could also use a Literal control and assign its Text property in your codebehind or use a Label if you require formatting.
You can put a label on the page where you want the text to appear and then set the label's text instead of doing like this. Simply put an asp label on the page and frmo your code behind do
myLabel.Text = HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString();
where myLabel is the ID of your label in your HTML Markup.
Define a DIV on the page like this, where you want the outputted string to be displayed:
<div id="myDIV" runat="server" />
Then, instead of r.Write() you can simply set the inner text of the DIV to be what you want:
myDIV.innerText = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
when you use Response.Write("..."); its shows up before page header , instead of using Response.Write you can put a label on the form wherever you want to see the message and set label's Text property.
Or if you just want the text, with no html markup.
Use a literal.
In aspx file
<asp:Literal ID="MyLiteral" runat="server" />
in code-behind
MyLiteral.Text = HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString();

HTML string does not get verified

These spaces are not added by me on HTML SIDE and i cannot edit HTML
I want to know what should my comparison string?
I am using watin to automate website testing process but I am unable to encounter only one button.Every other works
watin searches content by name /values /id and many more and works fine but when i see the value of the submit button that i need to be clicked it has some breaks &nsbp so i think they are playing some role
Here is the html:
<span class='button'><input type="submit" value=" Login " /></span>
<span class='button'><input type="button" value=" Back " onclick="history.back(-1)" /></span>
and here is the code to search
browser.Button(WatiN.Core.Find.ByValue(" Login ")).Click();
what can be done??
-- Suggestion -- (i.e. too big for a comment)
You shouldn't use to add spaces to the submit button. Rather, you should use CSS to style the button to your liking. So you would have something like:
input[type=button] {
padding:10px;
min-width: 150px;
}
By the same token, this could eliminate any of the issues you're having with selecting the button. It could be an issue of encodings breaking with watin and as a result, doing this with CSS will make debugging the issue much cleaner and much easier.
Edit:
Have you tried searching by ID as opposed to by value? ID's are supposed to be unique on a page, so if it doesn't find it by those means, then that's one issue that can be rules out. It could also be the fact that you're searching for a button. A <button> is not the same as a <input type="button">.
Edit 2: Even though the issue was due to encodings breaking, I still recommend you reset that button to reset the text (removing all the non breaking spaces) and attach an id/name to it. The reason being for internationalization purposes - and if for some reason you modify the size of the button in the designer, or i18n the app and the text is different, your test will break.
You shouldn't use entities with WatiN.
This code will work, but you have to use real non-breaking space character:
browser.Button(
WatiN.Core.Find.ByValue(
"   Login   ")).Click();
This is probably inconvenient, but you could use (after adding reference to System.Web) HttpUtility class:
browser.Button(
WatiN.Core.Find.ByValue(
System.Web.HttpUtility.HtmlDecode(
" Login "))).Click();
But, if I were you, I would just go with Regex:
browser.Button(
WatiN.Core.Find.ByValue(
new Regex(#"^\s*Login\s*$"))).Click();
or even new Regex("Login").
Interesting thing: If you ever will have to Find.ByText you don't have to bother so much, and you can use regular space (ie. not exactly non-breaking space). That's because native IE IHTMLElement::getAttribute (http://msdn.microsoft.com/en-us/library/aa752280(VS.85).aspx) converts from innertext attribute to regular spaces, but from value, id etc. it doesn't ( are converted to real non-breaking spaces - 0xA0)
Wow, you really like spaces! I would remove those and use padding/margins like html was designed to be used. Then you wont need all those spaces and you can assign a proper value to your button which watiN will recognize.
I think it is because the in the HTML source is actually an escaped version of the special character that represents a none breaking space. So in you C# source, you'll probably need that character instead of the html entity code. I think you can find the code of that character by using this button to submit a GET form. It will show the escaped character code in the url.
Of course it is better not to put the spaces in there at all. You should give the button a padding using CSS instead.

Categories