Control posts back http request, how do I get it? (asp.net) - asp.net

Request["ControlName"] doesn't work because I have been told the control is probably in a container... so how do I get the http request? The FORM part of the Request starts like this:
{__EVENTTARGET=ctl00%24lstThemeChooser&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=%2fwEP
lstThemeChooser is the name of my control...
Blue Theme
Orange Theme
defined in my masterpage aspx file

Attention! Pseudocode!
public interface IMyMasterPage
{
string ThemeChooserID { get; }
}
public partial class MyMasterPage : MasterPage, IMyMasterPage
{
public string ThemeChooserID { get { return lstThemeChooser.ClientID; } }
}
public MyPage : Page
{
protected void Page_PreInit(...)
{
string id = ((IMyMasterPage)this.Master).ThemeChooserID;
string val = Request[id];
}
}

ASP.NET prepends the container to the control name, so your control on the page is called ctl00%24lstThemeChooser.

Try
Request[lstThemeChooser.ClientID]

Related

About ASP.NET Web Pages Global

I am new learner to asp.net. I saw “_appstart.cshtml”, “_pagestart.cshtml” and “_viewstart.cshtml” which act like global headers or footer.
(1)If I want to trigger something right before the page is output, should I put the code in _viewstart.cshtml of others?
(2)Let C be the html code just before output, beside appending code to C can I replace code from C? Such as making all text uppercase or replace some text?
(3)Will asp.net cache this process so that I won't run each time?
benone
Answer to Point 1
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default
Actually it's like a BasePage in ASP.Net where we can keep the common code.
Or you can write the logic directly in the View like below.
#{
Layout = "~/Views/Shared/_Layout.cshtml";
if (Some Consition) {
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
}
Alternatively
You can override the Action Executing method, which executes before executing the Action Method. You can set it for a particular Action method or for the Complete Controller
Below is the code for setting it for Complete Controller.
protected override void OnActionExecuting(ActionExecutingContext ctx) {
base.OnActionExecuting(ctx);
}
Below is the Code for Setting it for Particular Action method
[MyAttribute(SomeProperty = "")]
public ActionResult Index()
{
return View("Index");
}
public class MyAttribute : ActionFilterAttribute
{
public string SomeProperty { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}
}
Answer to Point 2
You can use
var str = Html.Partial("_Partial_View_Name");
Partial returns an MvcHtmlString. You can intercept the output by setting it to a variable and make the necessary change.
Answer to Point 3
Yes. Below is the sample code
namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
[OutputCache(Duration=10, VaryByParam="none")]
public ActionResult Index()
{
return View();
}
}
}
The output of the Index() action is cached for 10 seconds

C# ASP.NET - Controlling/updating a textbox.text value through a class

Newbie here, I need help with a website I'm creating.
I have a class that does some analysis on some text that is input by the user, the class then finds an appropriate answer and sends it back to the textbox. (in theory)
Problem is I don't know how I can control and access the textbox on the default.aspx page from a class, all I get is "object reference is required non static field".
I made the textbox public in the designer file yet still no joy. :(
I've also read this: How can I access the controls on my ASP.NET page from a class within the solution? , which I think is along the lines of what I'm trying to achieve but I need clarification/step by step on how to achieve this.
Hope someone can point me in the right direction.
Many thanks,
Kal
This is the code I have added to the designer.cs file:
public global::System.Web.UI.WebControls.TextBox TextBox3;
public string MyTextBoxText
{
get
{
return TextBox3.Text;
}
set
{
TextBox3.Text = value;
}
}
This is the class method i have created:
public static cleanseMe(string input)
{
string utterance = input;
string cleansedUtt = Regex.Replace(utterance, #"[!]|[.]|[?]|[,]|[']", "");
WebApplication1._Default.TextBox3.text = cleansedUtt;
}
I could just return the cleansedUtt string i know, but is it possible for me to just append this string to the said textbox from this method, within this class?
I also tried it this way, i wrote a class that takes in the name of the textbox and string to append to that textbox. it works BUT only on the default.aspx page and does not recognise the textbox names within the difference classes. The code is as follows:
public class formControl
{
public static void ModifyText(TextBox textBox, string appendthis)
{
textBox.Text += appendthis + "\r\n";
}
I would suggest you that do not access the Page Controls like TextBox in your class. It will be more useful and a good practice that whatever functionality your class does, convert them into function which accept the parameters and returns some value and then on the basis of that value you can set the controls value.
So now you have reusable function that you can use from any of the page you want. You do not need to write it for every textbox.
Here I am giving you a simple example
public class Test
{
public bool IsValid(string value)
{
// Your logic
return true;
}
}
Now you can use it simple on your page like this
Test objTest = new Test();
bool result=objTest.IsValid(TextBox1.Text);
if(result)
{
TextBox1.Text="Everything is correct";
}
else
{
TextBox1.Text="Something went wrong";
}
If you have your class in the same project (Web Project) the following will work:
public class Test
{
public Test()
{
//
// TODO: Add constructor logic here
//
}
public static void ValidateTextBox(System.Web.UI.WebControls.TextBox txt)
{
//validation logic here
if (txt != null)
txt.Text = "Modified from class";
}
}
You can use this from your webform like this:
protected void Page_Load(object sender, EventArgs e)
{
Test.ValidateTextBox(this.txt);
}
If your class is in a different (class project), you would need to add a reference to System.Web to your project.

access controls on a asp.net master page from child page

i want to access a span on a asp.net master page from child page, so i'd made a public property on that master page-->
public partial class Ui_MasterPage_UI : System.Web.UI.MasterPage
{
public int tax = 0;
public string notification
{
set
{
(this.FindControl("notification") as HtmlAnchor).InnerText = value.ToString();
}
}
------------------//some code
}
and now wants to access this from a child page to set some text into that htmlanchor tag,
so that i'd written some script-->
child page
public partial class Ui_ProductDetails : System.Web.UI.Page
{
protected void ListView_ProductDetails_itemcommand(object sender, ListViewCommandEventArgs e)
{
Master.notification = "some text"; ////////showing error
------------------//some code
}
------------------//some code
}
but getting the syntax error
i think there is some problem in above code,,,,,so plz review it......
is there any other way to do this ???
thnku
You need to cast the Page.Master property to the type of your Master Page.
((Ui_MasterPage_UI)Page.Master).Notification = "some text";

Pass Data into User Control on Master Page from Sub Page

I have a user control on the master page and I would like to pass in a value into that user control from the subpage, how would I be able to pass the values?
This control is in the master page
<%# Register TagPrefix="test" TagName="Data" Src="controls/TEST.ascx" %>
This code variable is within the user control
public partial class Controls_TEST : System.Web.UI.UserControl
{
private string _Title;
public string Title
{
get { return _Title; }
set { _Title = value; }
}
}
Code within the subpage
public partial class sub_page : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Controls_Test m = LoadControl("~/Controls/TEST.ascx");
m.Title = "TEST";
}
}
Note the sample code within subpage does not work because it cannot find that user control within the subpage.
I've tried Page.Master.FindControl and it also does not work for me. PLease help.
Use properties to communicate from your Page to your MasterPage and use properties to communicate from your MasterPage to the UserControl.
To get a reference to the control in your MasterPage you should provide a public property that returns it:
For example(in MasterPage):
public Controls_Test MyControl
{
get
{
return Controls_TEST1;
}
}
And you can call this property from one of your ContentPages in this way(f.e. if your master's type is named "SiteMaster"):
protected void Page_Load(object sender, EventArgs e)
{
((SiteMaster)Page.Master).MyControl.Title = "TEST";
}
As a rule of thumb: the more you encapsulate your controls, the more robust ,failsafe, maintanable and extendable your code will be.
Hence it would be better to provide only access to the Title rather than to the whole UserControl.
In MasterPage:
public String Title
{
get
{
return Controls_TEST1.Title;
}
set
{
Controls_TEST1.Title = value;
}
}
In the ContentPage:
((SiteMaster)Page.Master).Title = "TEST";
On this way you could change the logic and controls in your UserControl and MasterPage without having problems in your pages that already have accessed the UserControl directly.

Auto wiring of Property does not work for me

In my Asp.Net project I wanna use Property Auto-wiring, e.g. for my ILogger. Basically I placed it as Property into class where I need to use it. Like below.
public class UserControlBase : UserControl
{
public ILogger CLogger { get; set; }
....
}
public partial class IPTracking : UserControlBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
//it works
ILogger logger = ObjectFactory.GetInstance<ILogger>();
logger.LogInfo(string.Format("Client IP: {0}", ip));
//it does not work
CLogger.LogInfo(string.Format("Client IP: {0}", ip));
}
}
}
However when calling in inherited control, logger is null. I checked the container and it'a definitely set as above implementation shows. Below is setting which is called from Global.asax.
public static void SetupForIoC()
{
Debug.WriteLine("SetupForIoC");
ObjectFactory.Initialize(x =>
{
x.FillAllPropertiesOfType<ILogger>().Use<EntLibLogger>();
});
Debug.WriteLine(ObjectFactory.WhatDoIHave());
}
Thanks for any advice, tip? X.
Update:
- I didnt mentioned before, but its Asp.Net webforms 3.5.
- I can't see what I am missing. I guess it could be because the injection gets involved later in process and didnt get set in requested class.
Link to desc. of usage: http://structuremap.github.com/structuremap/ConstructorAndSetterInjection.htm#section7
Give something like this a shot.
FillAllPropertiesOfType<ILogger>().AlwaysUnique().Use(s => s.ParentType == null ? new Log4NetLogger(s.BuildStack.Current.ConcreteType) : new Log4NetLogger((s.ParentType)));
Check out another StackOverflow answer I have which discusses using StructureMap to auto wire loggers.
Where do you actually set the CLogger property on the user control? Also, if you wanted to use one logger within the page, you could have the User cotnrol do:
public ILogger CLogger
{
get
{
if (this.Page is PageBase)
return ((PageBase)this.Page).Logger;
else
return null;
}
}

Resources