i have 2 aspx files . I need to access a public function in b.aspx from a.aspx. How can i do that in asp.net using C#
My function from a.aspx is the following:
<script language="C#" runat="server">
public String user()
{
return l1.Text;
}
</script>
Ideally, don't. Don't put common logic in aspx files - put it in other classes which both pages can access. Code in a page should only be about displaying that page.
Don't forget that when you're displaying b.aspx, there is no instance of page a, logically. You could create a new one, but if you're trying to get the value of a label which was displayed previously to a user, or something like that, this could go badly wrong.
#Sir Jon says,Create a new Class for Properites
public class UserEntity()
{
public UserEntity(string user)
{
User = user;
}
public UserEntity()
{
}
public string User { get;set;}
}
then use and pass it on your pages:
var ent = new UserEntity();
ent.User = li.Text
Regards
While that's not an everyday task, it's still possible.
You could use cross-page posting, and then access the properties of the first page.
The MSDN article Cross-Page Posting in ASP.NET Web Pages describes it.
Related
So I have 2 master pages and one user control which is used on almost every page. Page may have one of 2 master pages and both master pages have one property common. It is a list variable that I need access. How do I know which master page is being used and then access it?
I am trying
MasterPage mp = (MasterPage)this.Page.Master;
but when I debug, I don't see the list property. mp.List doesn't work. Any idea on how to get this property?
Thanks in advance
Consider using a simple interface to make this easy.
public interface IHasProperty
{
List<string> MyVariable {get;set;}
}
public partial class MasterPage1 : (other stuff), IHasProperty
{
List<string> MyVariable {get;set;}
}
public partial class MasterPage2 : (other stuff), IHasProperty
{
List<string> MyVariable {get;set;}
}
then from the user control, you can access this by using something like this.
var myPropPage = Page.Master as IHasProperty;
if (myPropPage == null)
{
//this property isnt on the page.
return;
}
myPropPage.MyVariable.Add("new Value");// or whatever you needed to do with it.
Add a strongly typed reference to the master page on your aspx as so:
<%# MasterType VirtualPath="~/Site.Master" %>
Then in the code behind you can do this.Master without having to cast and the list should be accessible.
On my current project I need to add a functionality that allows the user to view a thumbnail of their uploaded PDF. I've found a handy component that achieves this (the basic version is free, but it's enough for my current needs). Anyways, the control is pretty outdated (2010), therefore there doesn't seem to be MVC support. On the demos they depict usage of the control as such:
The View's Markup:
<form method="post" runat="server" enctype="multipart/form-data">
<asp:Panel ID="thumbnailsPanel" runat="server" />
</form>
The thumbnail control is instantiated via code, the byte array which represents the thumbnail is passed to the control and the control is added to thumbnailsPanel
<script runat="server">
protected void DisplayThumbs_Click( object sender, System.EventArgs e )
{
Thumbnail thumbnail = new Thumbnail();
thumbnail.SessionKey = sessionID;
thumbnail.Index = i;
thumbnailsPanel.Controls.Add( thumbnail );
}
</script>
Given that I can't declare a Thumbnail control in my razor view, how would I used this control in MVC? I've spent a few hours trying to make this control MVC friendly to no avail, the best I've come up with is to include a .ASPX view (not.cshtml) in my project and render the Thumbnail control on that view. Obviously this is not desirable.
So how would you go about using a ASPX server controls in MVC? Is the idea a bad one altogether and should not be practised?
I worked around it in a project of mine by reimplementing the control as a HtmlHelper. Assuming the control isn't too complicated then it should work for you too. Do this:
Dump the Control's source using Reflector
Massage the source so it actually compiles (as source from Reflector doesn't usually compile straight away)
Identify what state the control has. Convert the state from member properties into members of its own new ViewModel class.
Find the Render method and convert it to a HtmlHelper that uses ViewContext.Writer
For example:
public class FooControl : Control {
public String Message { get; set; }
public override void Render(HtmlTextWriter wtr) {
wtr.WriteLine("<p>");
wtr.WriteLine( message );
wtr.WriteLine("</p>");
}
}
Becomes this:
public class FooViewModel {
public String Message { get; set; }
}
// This method should exist in a static Extensions class for HtmlHelper
public static void Foo(this HtmlHelper html, FooViewModel model) {
HtmlTextWriter wtr = html.ViewContext.Writer;
wtr.WriteLine("<p>");
wtr.WriteLine( model.Message );
wtr.WriteLine("</p>");
}
Let's say I have an ASCX user control that requires access to the current user's full name. An ASPX page contains this line at the top
<%# Register src="top.ascx" tagprefix="custom" tagname="top" %>
and this line in the body:
<custom:top runat="server" />
The ASPX file knows the user ID of the current user and could determine his full name. So how can I use the code run by the ASPX file to provide its information to the ASCX file?
Declare a property on the UserControl and have the parent page set it.
On your usercontrol:
public string FullName { get; set; }
On the aspx page either set it in the code behind
YourUserControl.FullName = FullName
or through markup
<custom:top runat="server" FullName="<%= SomeProperty %>" />
You could use the Page property of the user control and cast it to the instance of your page. Then, call the method of your page class to get the user name.
To make this work in a dynamically compiled project, you have to do a little more work to have the control recognize the data type of the dynamically compiled page. Here is a short tutorial on how to do.
Or, as Brandon outlines, do the opposite and let your page tell your user control the information.
This sounds like you might be mistaken about how the page lifecycle works and how you can expose data across your controls. For example, lets say you have this code in your ASPX:
public override void OnLoad(EventArgs e)
{
string userName = "Bob";
}
In your ASPX file, you can reference the control and set a property on it to pass the data along:
<custom:top ID="someControl" runat="server" />
You expose a property in your top control like so:
public string UserName { get; set; }
You could then add this code to your OnLoad method:
someControl.UserName = userName;
Then your control will have access to that data. Alternatively, you can stick things in the Request cache if you dont have a direct line to the control:
HttpContext.Current.Items["key"] = userName;
And then pull the data from your control via the same fashion:
string fromCache = HttpContext.Current.Items["key"];
You could go about this in several ways. I typically use a session variable, since the user will be bound to the session.
In the ASPX (or when the user logs in):
Session["UserFullName"] = GetFullName(); //Code to get full name here
In the ASMX:
this.FullName = Session["UserFullName"]; //TODO: Check for null values
I would like to change dynamically the page theme in a MVC 2 Application.
I found several solutions, but I want to use this method: in the Global.asax, change the current page theme:
protected void Application_PreRequestHandlerExecute(object sender, System.EventArgs e)
{
// cast the current handler to a page object
Page p = HttpContext.Current.Handler as Page;
if (p != null)
{
string strTheme = "Theme1";
if (Convert.ToString(HttpContext.Current.Session["THEME"]) != string.Empty)
strTheme = Convert.ToString(HttpContext.Current.Session["THEME"]);
p.StyleSheetTheme = strTheme;
}
}
But this code always returns null in "p"...
I've also tried a similar code using the event PreRequestHandlerExecute in a HttpModule and the PreInit event of a page, but the code
HttpContext.Current.Handler as Page
always returns null.
Can anyone help me?
Thank you in advance.
I don't use baked in themes, but I do use jQuery UI themes. The way I handle it is in my master page I have logic that gets the current theme from a common viewmodel. The master page is strongly typed to this view model. The common viewmodel properties are updated from user preferences and other sources in a common base controller that all my controllers inherit. I do this in OnActionExecuted. I check if the result is a ViewResult, then cast the result from ViewData on the ActionExecutedContext.Result property to my common view model and set the property. The master page uses the value of the property to build the url for the CSS file.
Model
public abstract class CommonViewModel
{
public string Theme { get; set; }
// ...
}
Controller
public abstract class BaseController : Controller
{
public override void OnActionExecuted( ActionExecutedContext context )
{
if (context.Result is ViewResult)
{
var model = ((ViewResult)context.Result).ViewData.Model as CommonViewModel;
if (model != null)
{
var preferences = ...get from database for current user...
model.Theme = preferences.Theme;
}
}
}
}
Master note it uses a custom HtmlHelper to generate the stylesheet link, you could
do it by hand.
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<...CommonViewModel>" >
<%: Html.Stylesheet( "themes/" + Model.Theme + ".css" ) %>
The technique you are talking about works for standard asp.net, not asp.net MVC. The reason is that (in general) asp.net MVC does not use the web control model that standard asp.net does, and as such there is nothing to interpret the theme setting.
#tvanfosson has some great advice. Just remember that with MVC, you have much more control over things.. but that also means you have to do more work to get some of the features that standard asp.net provides for free. MVC makes many things easier, but this is not one of them.
Is there a way to get a value I am storing in a Master Page hidden field from a User Class which I created and placed in the App_Code folder of my ASP.Net 2.0 Application?
Some examples would preferably in VB.Net is highly appreciated.
Thanks.
To give further details, assume the following:
MasterPage.Master
MasterPage.Master.vb
MyPage.aspx
Mypage.aspx.vb
IN the app_code folder, add a new class, say TESTClass.
I have placed some logic in master page. MyPage.aspx uses the Masterpage.master as its master page. In the master page, the logic which I did stores a value into a hidden field.
in my TestClass, how do I access the master page hidden field?
Please take note that TestClass is NOT a user control but a user defined class, which contains some Business-Specific logic which is accessed by myPage.aspx.vb.
I tried ScarletGarden's suggestion but it did not seem to get the Masterpage Hiddenfield which I need to get the value.
Would something like this work?
((HiddenField)this.Page.Master.FindControl("[hidden control id]")).Text
You can get it by these :
hiddenControlValue = HttpContext.Current.Request["hiddenControlId"]
or you can pass your page to your method that belongs to your class under App_Config, and reach it as :
public static string GetHiddenValue(Page currentPage)
{
return currentPage.Request["hiddenValue"];
}
or you can get it over context :
public static string GetHiddenValue()
{
return HttpContext.Current.Request["hiddenValue"];
}
hope this helps.
EDIT: I re-read the question after answering, and realize my answer was probably not quite what you were after. :/
Jared's code might work, but you can also try the following.
In your MasterPage, make the HiddenField a public property, and store the content in the ViewState to make keep it during post backs.
Something like so:
public HiddenField theHiddenField
{
get
{
if (ViewState["HiddenField"] == null)
return null; //or something that makes you handle an unset ViewState
else
return ViewState["HiddenField"].ToString();
}
set
{
ViewState["HiddenField"] = value;
}
}
You then have to add the following to your ASCX-file:
<%# Reference Control="~/Masterpages/Communication.Master" %>
You then access it thusly.
Page mypage = (Page) this.Page; // Or instead of Page, use the page you're actually working with, like MyWebsite.Pages.PageWithUserControl
MasterPage mp = (MasterPage) mypage.Master;
HiddenField hf = mp.theHiddenField;
Sorry if the answer got a bit messy. This is, of course, how to do it in C#, if you want to use VB have a look at this link for the same idea.