I am currently trying to create a statement where if it returns false then a label will display on the page with an error message. I have tried using Response.Write with no results.
if (bannedDomainText.Text.Contains("."))
File.AppendAllText(MapPath(FILE_PATH), "\r\n" + bannedDomainText.Text);
else
Response.Write("<label>This isn't working!</label>");
Html
<asp:Label ID="ErrorMessage" Visible="false"></asp:Label>
Code
if (bannedDomainText.Text.Contains("."))
File.AppendAllText(MapPath(FILE_PATH), "\r\n" + bannedDomainText.Text);
else
{
Message.Text = "This is working";
Message.Visible = true;
}
Define a server side label and assign the message to its text property. You can hide this label or set its text to empty string when you do not want to show the message.
In Html
<asp:Label id="lblMessage" runat="server" />
In Code Behind
if (bannedDomainText.Text.Contains("."))
File.AppendAllText(MapPath(FILE_PATH), "\r\n" + bannedDomainText.Text);
else
lblMessage.Text = "This is working";
Related
This is my heading that i want to change from my c# code
<h3>Please Enter a number between 1 &
<asp:Label ID="lbl_max" runat="server"></asp:Label>
</h3>
I want to replace it with a string
string message = "This is new heading...";
i was thinking about something like this
lbl_max.value = message;
But it's not working... I am absolutely new to asp.net, so forgive me if it's a stupid question...
You can do it like this:
this.lbl_max.Text = "This is new heading...";
I have asked a question similar to this before, where I needed the link changed to something else, but I actually need to shorten the link instead of replacing it.
So I need to shorten links, when they are longer than...say...50 characters. I know how to change the link but can't figure out how to shorten it.
For example: http://www.google.com would shorten to something like http://google...
My code:
<%# BuildLink(Eval("TaskDefinition.Url").ToString(),Eval("TaskInstanceID").ToString())%>
I've done this, which replaces the link. But I need to shorten it, instead of replacing it.
<asp:HyperLink runat="server"
NavigateUrl='<%# BuildLink(Eval("TaskDefinition.Url").ToString(), Eval("TaskInstanceID").ToString())%>'>
My Link
</asp:HyperLink>
My BuildLink method:
public string BuildLink(string baseUrl, string taskInstanceId)
{
if (!string.IsNullOrEmpty(baseUrl))
{
string parms =
"taskinstanceid=" + taskInstanceId +
"&callback=" + GetCallBackUrl();
string url = baseUrl.Contains("?")
? baseUrl + "&" + parms
: baseUrl + "?" + parms;
bool isUnc = false;
try
{
Uri uri = new Uri(baseUrl);
isUnc = uri.IsUnc;
}
catch { }
string link;
if (isUnc)
{
link = "<a href='" + baseUrl + "' >" + baseUrl + "</a>";
}
else
{
link = "<a href='" + url + "' >" + baseUrl + "</a>";
}
return link;
}
return "";
}
This is the current view. Everything where it belongs
This is the view that's generated with the code JF gave
Also, the links are shortened even though they aren't 50> which is odd... I dislike asp repeaters.
An <asp:Hyperlink> also gives you the ability to set the text to be displayed. So similar to how you build the link, you can also trim the text.
First, set the text attribute. You can also remove the text from in between the hyperlink tags as the text attribute does this for you.
<asp:HyperLink runat="server"
NavigateUrl='<%# BuildLink(Eval("TaskDefinition.Url").ToString(), Eval("TaskInstanceID").ToString())%>'
Text='<%# TrimLink(Eval("TaskDefinition.Url").ToString(), Eval("TaskInstanceID").ToString())%>'>
</asp:HyperLink>
Then, create your code behind method. In this method, do you logic to get the full text of the URL that will be displayed. Check the length of that text. If the length is longer than 50, Substring() it to 50 characters and concatenate some ellipsis onto it.
public string TrimLink(string baseUrl, string taskInstanceId)
{
string urlText = "";
// do your logic to get the full url
if(urlText.Length > 50)
{
urlText = urlText.Substring(0, 50);
urlText = urlText + "...";
}
return urlText;
}
Instead of returning an entire hyperlink to be used as the URL for the <asp:Hyperlink>, try returning just the URL instead. I'm wondering if all the extra characters are unintentionally being used as closings for other controls. In BuildLink, do this instead.
if (isUnc)
{
link = baseUrl;
}
else
{
link = url;
}
return link;
i'm having issues with code that used to work, but now fails to run. I have a character counter on a textbox with the below code in the .aspx file:
<script>
var bName = navigator.appName;
function taLimit(taObj, maxL) {
if (taObj.value.length == maxL) return false;
return true;
}
function taCount(taObj, Cnt, maxL) {
objCnt = createObject(Cnt);
objVal = taObj.value;
if (objVal.length > maxL) objVal = objVal.substring(0, maxL);
if (objCnt) {
if (bName == "Netscape") {
objCnt.textContent = maxL - objVal.length;
}
else { objCnt.innerText = maxL - objVal.length; }
}
return true;
}
function createObject(objId) {
if (document.getElementById) return document.getElementById(objId);
else if (document.layers) return eval("document." + objId);
else if (document.all) return eval("document.all." + objId);
else return eval("document." + objId);
}
</script>
aspx:
<asp:TextBox ID="txtDescription" runat="server" Font-Names="Courier New"
TextMode="MultiLine" Width="398px" onKeyPress="return taLimit(this, 50)" onKeyUp="return taCount(this,'myCounter1', 50)"></asp:TextBox>
<br /><B><SPAN id='myCounter1'>50</SPAN></B>
This worked without problems before, but now i want a way to update the myCounter1 On page load, to show the correct remaining characters, i'm loading text from database into the textbox.
right now i'm using this:
ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript", "document.getElementById('myCounter1').textContent = 50 - " + txtDescription.Text.Length.ToString() + ";", true);
This works, it sets the character counter to the correct remaining characters. Now the issue is however, when text is typed in the textbox, the caracter counter won't update anymore dynamically. Could someone tell me why?
Using js. Put this inside your script:
<script type="text/javascript">
window.onload = function(){
taCount(document.getElementById('<%=txtDescription.ClientID%>'),'myCounter1', 50);
}
</script>
Remove the Server side scriptmanager code.
Having a strange problem regarding the postback of a form I've created. The answer will probably be really simple, but I can't seem to see it.
I have a form that a user can fill in if the page a video is on, isn't working. It pre-populates fields based on the current video selected, and allows the user to fill in other fields, and send the email to me for support.
The problem
The fields are pre-populated correctly, but one of the fields 'Page', although pre-populated correctly, doesn't pass the value to the button submit method.
the clientside code
(includes some mootools javascript, this works)
<asp:Panel ID="pnlVideoProblem" runat="server" Visible="false">
<h2>Report a video/learning tool issue</h2>
<div class="keyline"></div>
<fieldset class="emailform">
<ul>
<li><label>Name <span class="error">*</span></label><asp:TextBox ID="txtVideoName" runat="server" MaxLength="60"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator33" runat="server" CssClass="error" ControlToValidate="txtVideoName" ErrorMessage="Required"></asp:RequiredFieldValidator></li>
<li><label>Email <span class="error">*</span></label><asp:TextBox ID="txtVideoEmail" runat="server" MaxLength="100"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator35" runat="server" CssClass="error" ControlToValidate="txtVideoEmail" ErrorMessage="Required"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator7" runat="server" ControlToValidate="txtVideoEmail" Text="Invalid email" ErrorMessage="Email address is not in the correct format" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator></li>
<li><label>OTHER FIELD</label><asp:TextBox ID="txtOtherField" runat="server" MaxLength="10"></asp:TextBox></li>
<li><label>Video ID</label><asp:TextBox ID="txtVideoID" runat="server" ReadOnly="true"></asp:TextBox></li>
<li><label>Browser/Version </label><asp:TextBox ID="txtVideoBrowser" runat="server" MaxLength="100"></asp:TextBox></li>
<li><label>Flash Version </label><asp:TextBox ID="txtFlashVersion" runat="server"></asp:TextBox></li>
<li><label>Page </label><asp:TextBox ID="txtVideoPage" runat="server"></asp:TextBox></li>
<li><label>Visible error messages </label><asp:TextBox ID="txtVisError" runat="server" TextMode="MultiLine" Rows="6" MaxLength="4000"></asp:TextBox></li>
</ul>
<asp:Button ID="btnSubmitVideoIssue" runat="server" CssClass="subbutton" Text="Submit report" OnClick="btnSubmitVideoIssue_Click" />
</fieldset>
<script type="text/javascript">
window.addEvent('domready', function () {
document.id('<%= txtVideoBrowser.ClientID %>').set('value', Browser.Platform.name + ", " + Browser.name + " " + Browser.version);
document.id('<%= txtFlashVersion.ClientID %>').set('value', Browser.Plugins.Flash.version + "." + Browser.Plugins.Flash.build);
});
</script>
</asp:Panel>
the page-behind code for the button
(there is no reseting of the values on postback)
protected void btnSubmitVideoIssue_Click(object sender, EventArgs e)
{
if (CheckEmptyCaptcha() == false)
{
//this field is hidden in css and empty. if it has been filled in, then an automated way of entering has been used.
//ignore and send no email.
}
else
{
StringBuilder sbMessage = new StringBuilder();
emailForm = new MailMessage();
sbMessage.Append("Name : " + txtVideoName.Text.Trim() + "<br>");
sbMessage.Append("Email : " + txtVideoEmail.Text.Trim() + "<br>");
sbMessage.Append("Other Field : " + txtOtherField.Text.Trim() + "<br>");
sbMessage.Append("Video ID : " + txtVideoID.Text.Trim() + "<br>");
sbMessage.Append("Browser : " + txtVideoBrowser.Text.Trim() + "<br>");
sbMessage.Append("Flash Version : " + txtFlashVersion.Text.Trim() + "<br>");
sbMessage.Append("Visible error messages : " + txtVisError.Text.Trim() + "<br>");
sbMessage.Append("Url referrer : " + txtVideoPage.Text.Trim()+"<br>");
sbMessage.Append("Browser : " + Request.UserAgent + "<br>");
if (txtVideoBrowser.Text.Contains("ie 6"))
{
sbMessage.Append("<strong>Browser note</strong> : The PC that made this request looks like it was using Internet Explorer 6, although videos work in IE6, the browser isn't stable software, and therefore Javascript errors may occur preventing the viewing of the page/video/learning tool how it was intended. Recommend that the user upgrades their browsers to the latest version of IE.<br>");
}
Double flashver = 0.0;
if(Double.TryParse(txtFlashVersion.Text, out flashver))
{
if(flashver < 9.0)
{
sbMessage.Append("<strong>Flash version note</strong> : The PC that made this request is currently using flash version "+flashver+". Flash version 9 or greater is required to view videos. Recommend user upgrades their flash version by visiting http://get.adobe.com/flashplayer<br>");
}
}
else
{
sbMessage.Append("<strong>Flash version note</strong> : It doesn't look like flash is installed on the PC that made this request. Flash is required to view videos . Recommend user installs flash by visiting http://get.adobe.com/flashplayer<br>");
}
emailForm.To.Add(new MailAddress("admin#test.com"));
emailForm.From = new MailAddress(txtVideoEmail.Text.Trim(), txtVideoName.Text.Trim());
emailForm.Subject = "[ERROR] - [VIDEO ISSUE] from " + txtVideoName.Text.Trim();
emailForm.Body = sbMessage.ToString();
emailForm.IsBodyHtml = true;
bool sendSuccess = false;
try
{
SmtpClient smtp = new SmtpClient();
smtp.Send(emailForm);
sendSuccess = true;
}
catch
{
pnlVideoProblem.Visible = false;
pnlFailure.Visible = true;
ltlFailure.Text = "There was a problem sending your feedback, please go back and try again.";
}
finally
{
if (sendSuccess)
{
pnlVideoProblem.Visible = false;
pnlSuccess.Visible = true;
ltlSuccess.Text = "Thank you, your feedback has been sent. Click close to return to the website.";
}
else
{
pnlVideoProblem.Visible = false;
pnlFailure.Visible = true;
ltlFailure.Text = "There was a problem sending your feedback, please go back and try again.";
}
}
}
}
the form values
Name : User
Email : User#test.com
Other Field : aab123
Video Learning ID : 5546
Browser version : win, firefox 9
Flash version : 11.102
Page : https://www.awebsite.com/library/video/5546
Visible error messages : ewrwerwe
the resulting email
Name : User
Email : user#test.com
Other Field : aab123
Video ID : 5546
Browser : win, firefox 9
Flash Version : 11.102
Url referrer :
Visible error messages : ewrwerwe
Video ID and Page/Url Referrer are populated on (!IsPostBack)
(!IsPostBack)
pnlVideoProblem.Visible = true;
if (!String.IsNullOrEmpty(Request.QueryString["vid"]))
{
txtVideoID.Text = Request.QueryString["vid"];
}
if (!String.IsNullOrEmpty(Request.QueryString["other"]))
{
txtOtherField.Text = Request.QueryString["other"];
txtOtherField.ReadOnly = true;
}
txtVideoPage.Text = HttpUtility.UrlDecode(Request.QueryString["ref"]);
txtVideoPage.ReadOnly = true;
any ideas? I have a brick wall i can hit my head against based on how simple the answer is.
If TextBox's ReadOnly property is "true", postback data won't be
loaded e.g it essentially means TextBox being readonly from
server-side standpoint (client-side changes will be ignored).
If you want TB to be readonly in the "old manner" use:
TextBox1.Attributes.Add("readonly","readonly")
as that won't affect server-side functionality.
From: http://aspadvice.com/blogs/joteke/archive/2006/04/12/16409.aspx
See also: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.readonly.aspx
Solved :)
After a tiny ray of sunshine i remembered I had this
RewriteRule ^/pop/(.*[^/])/report-issue/([a-fA-F0-9]{32})-([0-9]+)$ /pop.aspx?tp=$1&pg=report-issue&vid=$2&other=$3&ref=%{HTTP_REFERER} [L]
as a rewrite rule, which then led me to take a closer look at whether the form fieldswere actually was wrapped in a postback. Lo-and-behold, they werent.
I've wrapped a !postback around the querystring variable reading section and it works!
brick wall needs to be very thick.
thanks to those that tried to help!
I need that some html in the area in the asp.net page that i am coding, is changed according to a string variable.
I was thinking about creating a label, and then change the text on it.
But the string variable contains something like:
<h2><p>Notify:</p> alert</h2>
So, I don't feel that give this to a label text is a good idea
How i can do?
Using response.write?
If I use response.write, my added code will be at the beginning of the html source, how i can tell him to add it in a specific ?
Thank you
If you really don't want to use any server controls, you should put the Response.Write in the place you want the string to be written:
<body>
<% Response.Write(stringVariable); %>
</body>
A shorthand for this syntax is:
<body>
<%= stringVariable %>
</body>
why don't you give LiteralControl a try?
myLitCtrl.Text="<h2><p>Notify:</p> Alert</h2>";
If you want something lighter than a Label or other ASP.NET-specific server control you can just use a standard HTML DIV or SPAN and with runat="server", e.g.:
Markup:
<span runat="server" id="FooSpan"></span>
Code:
FooSpan.Text = "Foo";
ASPX file:
<h2><p>Notify:</p> <asp:Literal runat="server" ID="ltNotify" /></h2>
ASPX.CS file:
ltNotify.Text = "Alert!";
Use a literal control and write your html like this:
literal1.text = "<h2><p>Notify:</p> alert</h2>";
You should really use the Literal ASP.NET control for that.
You can go with the literal control of ASP.net or you can use panels or the purpose.
You can also use pageMethods in asp.net. So that you can call javascript functions from asp.net functions. E.g.
[WebMethod]
public static string showTxtbox(string name)
{
return showResult(name);
}
public static string showResult(string name)
{
Database databaseObj = new Database();
DataTable dtObj = databaseObj.getMatches(name);
string result = "<table border='1' cellspacing='2' cellpadding='2' >" +
"<tr>" +
"<td><b>Name</b></td>" +
"<td><b>Company Name</b></td>" +
"<td><b>Phone</b></td>"+
"</tr>";
for (int i = 0; i < dtObj.Rows.Count; i++)
{
result += "<tr> <td><a href=\"javascript:link('" + dtObj.Rows[i][0].ToString().Trim() + "','" +
dtObj.Rows[i][1].ToString().Trim() +"','"+dtObj.Rows[i][2]+ "');\">" + Convert.ToString(dtObj.Rows[i]["name"]) + "</td>" +
"<td>" + Convert.ToString(dtObj.Rows[i]["customerCompany"]) + "</td>" +
"<td>"+Convert.ToString(dtObj.Rows[i]["Phone"])+"</td>"+
"</tr>";
}
result += "</table>";
return result;
}
Here above code is written in .aspx.cs page. Database is another class. In showResult() function I've called javascript's link() function.
Result is displayed in the form of table.