Set .aspx page title to that of an Eval - asp.net

I am trying to use an <%# Eval("name") %> to be the title of my page. I can't seem to figure out any solutions online. I have tried the other StackOverflow question but that did now work either.
The page is a bio.aspx and on the site it is displayed as bio.aspx?id=123 so the page title needs to vary depending on the ID. I figured I could just use the Eval("name") but no luck yet.
I currently am using JavaScript:
window.onload = function() {
document.title = '<%# Eval("name") %> | Title Line';
}
This works, but it still leaves the title tags empty, and it's kind of spammy.
Here is the codebehind:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class DoctorBio : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Page.Title = "Your Page Title";
HtmlMeta metaDescription = new HtmlMeta();
metaDescription.Name = "description";
metaDescription.Content = "brief description";
Page.Header.Controls.Add(metaDescription);
HtmlMeta metaKeywords = new HtmlMeta();
metaKeywords.Name = "keywords";
metaKeywords.Content = "keywords, keywords";
Page.Header.Controls.Add(metaKeywords);
}
protected void SetPageTitle(object title)
{
this.Title = title.ToString();
}
protected string ReplaceLineBreaks(object text)
{
string newText = text as string;
if (newText == null) { return string.Empty; }
return newText.Replace("\r\n", "<br />");
}
}

Replace your following code
Previous code
this.Title = title.ToString();
Replace with
Page.Title = title.ToString();
Try this one. It is working for me...

Related

ASP.NET Eventhandler Not working

I have a pretty straight forward dynamically generated asp page. This is my first time using dynamically generated asp controls. The table renders correctly, however when I click on the "Query" button I cannot get the event to connect to the "OnClick" method. I get a webpage error "'ButtonClick' is undefined". I have stripped and simplified the code down for brevity.
DeviceStatus.aspx
<%# Page Title="Device Status" Language="C#" MasterPageFile="Secure.master"
'AutoEventWireup="true" CodeFile="DeviceStatus.aspx.cs" Inherits="Devices" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"></asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div id="selectDiv" runat="server"></div>
</asp:Content>
DeviceStatus.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Devices : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
int i, NumberOfDevices = 3;
string Contents;
string[] number = new string[] { "1", "2", "3"};
string[] name = new string[] {"mike", "bob", "cindy"};
string[] location = new string[] { "Austin", "Miami", "Atlanta" };
// Create event binding
PlaceHolder Placeholder1 = new PlaceHolder();
Button button = new Button();
button.Text = "Click";
button.Click += new System.EventHandler(ButtonClick);
Placeholder1.Controls.Add(button);
//Create Form and table header
Contents = "<form runat=\"server\"><table border=\"1\" >";
Contents += "<tr><th>Select</th><th>Number</th><th>Name</th><th>Status</tr>";
// Repeat for each table row
for (i = 0; i < NumberOfDevices; i++) {
// Creat each row
Contents += "<tr><td><asp:Button ID=\"row" + i + "\""
+ "runat=\"server\"OnClick=\"ButtonClick\" >Query</asp:Button></td>"
+ "<td>" + number[i] + "</td><td>" + name[i] + "</td><td>"
+ location[i] + "</td></tr>";
}
// Cleanup
Contents += "</table>";
Contents += "<asp:PlaceHolder ID=\"Placeholder1\" runat=\"server\"></asp:PlaceHolder>";
Contents += "</form>";
Contents += "</asp:Content>";
//Place dynamic asp controls in webpage
selectDiv.InnerHtml = Contents;
}
protected void ButtonClick(object sender, EventArgs e)
{
Response.Redirect("DataRendering.aspx");
}
}
I went with Garrison's suggestion. It took some time to get through the code to figure it out but once completed was the most straight forward solution. Thanks everyone for contributing.

using functions in code behind on webpage

Disclaimer: I'm pretty new to ASP.NET, so I'm figuring it out as I go along.
I'm trying to output the results of a function in my code behind page on the webpage itself.
Example:
Code Behind:
public string POSTResult(string e) { ... return TheResult; }
ASPX Page:
Output is: <%=POSTResult("argument")%>
However, loading the page errors, saying "The name 'POSTResult' does not exist in the current context."
I'm apparently doing something a bit off with how I'm getting to the code behind page from the ASPX page. My ASPX page has this at the top:
<%# Page Title="" Language="C#" MasterPageFile="~/master/default.Master" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="Bitfork.login" %>
The listed CodeBehind value is the name of the code behind page.
ETA:
Contents of my code behind (login.aspx.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
namespace Bitfork.master
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string POSTResult(string e)
{
// variables to store parameter values
string url = "https://accounts.google.com/o/oauth2/token";
// creates the post data for the POST request
string postData = (e);
// create the POST request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postData.Length;
// POST the data
using (StreamWriter requestWriter2 = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter2.Write(postData);
}
// This actually does the request and gets the response back
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
string responseData = string.Empty;
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
// dumps the HTML from the response into a string variable
responseData = responseReader.ReadToEnd();
}
return responseData;
}
}
}
Example of argument being passed, with API secret keys redacted:
code=[redacted]&client_id=[redacted]&client_secret=[redacted]&redirect_uri=http://localhost:60284/login.aspx&grant_type=authorization_code
ETA2:
I don't know if it's related, but it seems like my code behind page and my webpage are not communicating with each other at all. For instance, I can't access DIVs by ID in my code behind page to change their contents.

How to get label's text by HTTP handler (.ashx) in repeater control

I have a label within a <table> in a repeater. I have an HttpHandler named "NameShow.ashx" to return the "name" as "text/plain" by passing an "id" to the handler.
I want to retrieve the "name" (similar to retrieving "image" from handler).
Here is my code:
<asp:Label ID="Label1" runat="server" Text='<%#""NameShow.ashx?id="+Eval("id") %>'>
</asp:Label>
I am getting the text of this label as ->> NameShow.ashx?id=123
Please help in finding where I am doing mistake.
Here is my Haldler code.
using System;
using System.Web;
public class NameShow : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
string strid = context.Request.QueryString["id"];
long pro_id = int.Parse(strid);
string name = DBHelpername.name(pro_id);
context.Response.ContentType = "text/plain";
context.Response.Write(name);
}
public bool IsReusable {
get {
return false;
}
}
}
Here is my DBHelper code:
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
/// <summary>
/// Summary description for DBHelpername
/// </summary>
public class DBHelpername
{
public DBHelpername()
{
//
// TODO: Add constructor logic here
//
}
public static string name(long id)
{
SqlConnection connect = new SqlConnection
("Data Source=DELL-36B3EF6E9F;Integrated Security=True;Initial Catalog=pool");
connect.Open();
SqlCommand sc =
new SqlCommand("SELECT name FROM Profile WHERE profile_id=" + id + "", connect);
SqlDataAdapter da = new SqlDataAdapter(sc);
DataSet ds = new DataSet();
da.Fill(ds);
string nameret = ds.Tables[0].Rows[0][0].ToString();
return nameret;
connect.Close();
}
}
If you are not married to the idea of using an HTTP Handler, then I suggest making a method in your .aspx page's code-behind that does the same logic your handler is doing minus the content-type stuff, like this:
protected string GetName(int pro_id)
{
return DBHelpername.name(pro_id);
}
Now in your markup you can use this method, like this:
<asp:Label ID="Label1" runat="server" Text='<%# GetName((int)Eval("id")) %>'>
</asp:Label>
<%# new System.Net.WebClient().DownloadString("http://www.yoursite.com/NameShow.ashx?id="+Eval("id"))) %>
Something like this may work, although you might need to re-think your approach as you are going do a http request for each item in your repeater - and that isn't going to scale well! It looks like this is all in one application/website, so can you not call the code that looks up the name in the codebehind of this page?

AjaxPro for .NET

I am new to Ajax .I have used AjaxPro In ASPX page for executing method .I have used below code for .NET 2.0
In ASPX:
$(function() {
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight",
update: function(event, ui) {
var order = $('#sortable').sortable('serialize');
var retStr = SortTest.Save(order);
}
});
$( "#sortable" ).disableSelection();
});
</script>
In CS file:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using Ajaxpro;
public partial class SortTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(SortTest));
}
[AjaxPro.AjaxMethod]
public string Save(string corder)
{
return "Test";
}
}
Its working fine,but when i using in .NET 1.1 (AjaxPro.JSON.dll),its not working and even though i didn't get how to register.Plz do help me ajaxpro for .NET1.1 .
as i see in your there is no namespace. try to use namespace first. then Call your Ajax method by using Namespace.ClassName. some thing like this.
[AjaxNamespace("SortNameSpace")]
public partial class SortTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(SortTest));
}
[AjaxPro.AjaxMethod]
public string Save(string corder)
{
return "Test";
}
}
while calling from javascript try like this
var retStr = SortNameSpace.SortTest.Save(order).value; //do something with returned value

Ashx handler cannot be used through an <asp:Image> control

In an ASP.NET 3.5 application, I have created an ashx handler as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Services;
namespace TestWebConfig
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpg";
BinaryReader br = new BinaryReader(File.Open( #"d:\Temp\images\AutumnLeaves.jpg", FileMode.Open ));
int bufferLength = 1000;
do
{
byte[] buffer = br.ReadBytes(bufferLength);
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
if (buffer.Length < bufferLength)
{
break;
}
} while (true);
br.Close();
}
public bool IsReusable
{
get
{
return true;
}
}
}
}
In an aspx page, if I specify:
<img alt="alt2" src="Handler1.ashx" style="border-width:0px"/>
then the web page is loaded into the browser together with the image. On the other hand, if I use:
<asp:Image ID="Image2" runat="server" />
and in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
Image2.ImageUrl = "Handler1.asxh";
}
then the Image2 control does not load the picture, although the associated html code looks alike. Only the alt text is shown. What's wrong?
Thanks
For one thing in your Page_Load it looks like you've given it the wrong extension, but I don't think that's the problem.

Resources