textBox onBlur to call server method instead of client method - asp.net

I'm extending a web control. I need to call server methods on every event fired by the control instead of javascript.
public partial class MyTextBox : RadTextBox, IScriptControl
{
public MyTextBox()
{
Attributes.Add("onBlur", "handleLostFocus();");
Attributes.Add("runat", "server");
}
public void handleLostFocus()
{
MyObject obj = new MyObject();
obj.someproperty = this.Text; //or somehow get the user entered text.
MyService1 service = new MyService1();
service.sendRequest(obj);
}
}

As I said in my comment, TextBox will post by default if AutoPostBack = "True", however, you need to handle your event. Supposing your TextBox is named TextBox1:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
string str = TextBox1.Text;
}
Get rid of handleLostFocus() or have it be the handler for your TextBox control.
Good luck mate.

Related

Open aspx Page after WCF Callback

I've the following problem:
I have to implemented a kind of a chat application. Therefore I use ASP.NET 4.5 and WCF. When I'm start click on the person I want to chat with, I call a wcf webservice. This webservice calls the wcf callback from the person I clicked on it. My problem is now, that I get the event called on the client side, but I am not able to open a new ChatWindow.
[CallbackBehavior(UseSynchronizationContext = false, ConcurrencyMode = ConcurrencyMode.Single)]
public class ChatContext : IChatClient, INotifyPropertyChanged
{
#region Events
public event EventHandler StartChat;
#endregion
public void FollowChatBegin(Person invitee)
{
StartChat(invitee, new EventArgs());
}
I have registered the StartChat Event in my main page:
public partial class MainPage: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// ...
Global.ChatContext.StartChat += ChatContextOnStartChat;
}
private void ChatContextOnStartChat(object sender, EventArgs eventArgs)
{
var person= (Person) sender;
string path = this.Request.Url.AbsoluteUri.Remove(this.Request.Url.AbsoluteUri.IndexOf(Request.Url.LocalPath, Request.Url.LocalPath.Length));
path += "/Controls/Chat/ChatWindow.aspx";
string parameters = "did=" + person.Id + "height=700px,width=800px,resizeable=yes,status=no";
path += parameters;
ScriptManager.RegisterStartupScript(this, this.GetType(), "openChartWindow", "window.open('" + path + "');", true);
this.upMain.Update();
}
}
ChatContextOnStartChat gives me the following problems:
this.Request is null
I cannot call my UpdatePanel.Update
I have no idea how I can simply open a pop up / dialog whatever... Can I just use a wrong pattern?

Store and transfer values in a ascx control

I have a problem that I have been struggling with for some time, and it is regarding transfering values from one control to another.
Basically I have two .ascx controls. On control1: I have an email textbox called txtEmail. The txtEmail is used to save the email in the SQL table, and on update button click, I load Control2 that has a email textbox as well. I need the emailtext box from control1 to be available on email textbox on control2.
I have tried all kinds of different ways but to no avail. I even tried using delegates and events but I can't make it work.
Does anyone know how I can do this.
Regards
Please find below the code:
public event EventHandler Notify;
public string Email
{
get { return txtEmail.Text; }
set {Email= value ; }
}
//button that will handle the update
protected void btnUpdateDB_Click(object sender, EventArgs e)
{
var email = txtEmail.Text.ToString();
public BaseClass.BAL.MBAL m = new BaseClass.BAL.MBAL();
var s = new BaseClass.Controllers.m();
s.email=email;
if(m.save(s)!=0) txtMsave.Text="Saved....";
}
//second control
public void notifyEmailChange(object sender,EventArgs e)
{
txtUsername.Text = member1.Email;
}
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
member1.Notify += new EventHandler(notifyEmailChange);
}
}
public string email {
set { txtUsers.Text = value; }}
Maybe I am trivializing the problem, but if you are wanting to be able to read/write to the text box on each of the custom controls, just make a public property that reads and writes to the textbox on each of the two controls.
public string EmailAddress {
get {
return txtEmailAddress.Text;
}
set {
txtEmailAddress.Text = value;
}
}
Now the page that contains the two controls can read the email address from the first control and write it into the email address text box in the second control.
If I am misunderstanding the problem, let me know.
The way that I have done this in the past is to have
UserControl1 have a custom event called (for instance) Notify.
The containing control wires Notify to an EventHandler
When notify fires (on the update) the consuming event handler fires and this event handler updates the email on UserControl2
Might seem overengineered but because UserControl2 can't "see" UserControl1 I think this is the way to go
Example
In UserControl1
public event EventHandler Notify;
and within the update button click event handler
if(Notify != null)
{
Notify(this, new EventArgs());
}
In parent control
in Page_Load
ucUserControl2.Notify += new EventHandler(NotifyUserControl);
and to set the message
protected void NotifyUserControl(object sender, EventArgs args)
{
ucUserControl2.Email = ucUserControl1.Email;
}
You obviously need public properties in UserControls to expose the Email text

passing a value to WebUserControl for show in a lable

hi
i have a WebUserControl that have a lable for show message
how can i send a value to the lable from Page to my WebUserControl at runtime.
In the code behind file of your control you can specify an attribute
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public String customType
{
get
{
String s = (String)ViewState["customType"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["customType"] = value;
}
}
And after you can get this attribute to fill your label in the pageload with
mylabel.text = mycontrol.customType
In the asp page you specify the attribute (here is the 'customType'):
<wuc:ContSign customType="person" ID="ContSignPanel" runat="server" />
MSDN
You can create a public method in your user control such as
public void ShowMessage(string message)
{
Label1.Text = message;
}
Label1 being the label control in user control. Now you can use the method from Page as and when you need it - for example,
protected void Page_Load(object Sender, EventArgs e)
{
MyUserControl1.ShowMessage("Hello");
}
where MyUserControl1 is the name/ID of web user control put on the page.
just make a property to get and set values for the lable in the user control
private string _labelmsg;
public string LableMsg
get
{
return _labelmsg;
}
set
{
_labelmsg=lblID.Text;
}
and then set in the aspx.cs page like
UserControlID.LabelMsg="Set Any Value";

LinkButton.Command in user control (ascx) will not call specified method

I have the following code:
public partial class queryTerm : System.Web.UI.UserControl
{
private static readonly List<string> BooleanOperators = new List<string> { ".", "AND", "AND NOT", "OR", "OR NOT" };
protected void BuildBoolPanel()
{
var parensOpen = _labelBoolean.Text;
foreach (var #operator in BooleanOperators)
{
if (parensOpen == #operator)
{
continue;
}
var linkButton = new LinkButton();
linkButton.Text = #operator;
linkButton.CommandArgument = #operator;
linkButton.CommandName = "parensOpen";
linkButton.Command += new CommandEventHandler(linkButton_Command);
_popupMenuParensOpen.Controls.Add(linkButton);
var literalLineBreak = new Literal();
literalLineBreak.Text = "<BR/>";
_popupMenuParensOpen.Controls.Add(literalLineBreak);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
BuildBoolPanel();
}
void linkButton_Command(object sender, CommandEventArgs e)
{
_labelBoolean.Text = (string)e.CommandArgument;
BuildBoolPanel();
}
}
I have a panel(it's _popupMenuParensOpen) that is shown with the hoverextender whenever the cursor finds itself over a specific label in my user control.
This panel has all the boolean operators and '.' meaning not set.
I programatically add the boolean operators as a label in my panel, and I only add those that don't match what it is currently set to. For instance if my label is set to 'AND', when I hover over it, I display everything but 'AND'.
The problem is these never call linkButton_Command even though I instruct them to.
Weirder yet, if I remove the 'if (!this.IsPostBack) in page load, it will call it.
My control is inside an updatePanel.
The issue is that you're dynamically adding the controls during the Page_Load event. When a postback occurs those controls aren't going to exist and will need to be created every time. This is why when you remove your if (!Page.IsPostBack), and the controls are rebuilt, it works.
Since you're building this as a user control, you might want to look in to overriding the CreateChildControls method.

Custom TextBox with built-in Validator: server side validation not firing

I have a class that looks like this:
public class TextField : TextBox
{
public bool Required { get; set; }
RequiredFieldValidator _validator;
protected override void CreateChildControls()
{
base.CreateChildControls();
_validator = new RequiredFieldValidator();
_validator.ControlToValidate = this.ID;
if(Required)
Controls.Add(_validator);
}
public override void Render(HtmlTextWriter tw)
{
base.Render(tw);
if(Required)
_validator.RenderControl(tw);
}
}
This has been working for a while in a internal application where javascript is always enabled. I recently noticed that an upstream javascript error can prevent the validators from firing, so the server side validation should kick in... right? right?
So the Page.IsValid property always returns true (I even tried explicitly calling Page.Validate() before-hand).
After some digging, I found that the validator init method should add the validator to the page, but due to the way I'm building it up, I don't think this ever happens. Thus, client side validation works, but server side validation does not.
I've tried this:
protected override OnInit()
{
base.OnInit();
Page.Validators.Add(_validator); // <-- validator is null here
}
But of course the validator is null here (and sometimes it's not required so it shouldn't be added)... but OnInit() is really early for me to make those decisions (the Required property won't have been loaded from ViewState for example).
Ideas?
The CreateChildControls is basically for the controls that have childs. RequiredFieldValidator is like a sibling to TextBox.
Here is the code that works for me:
public class RequiredTextBox : TextBox
{
private RequiredFieldValidator _req;
private string _errorMessage;
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; }
}
protected override void OnInit(EventArgs e)
{
_req = new RequiredFieldValidator();
_req.ControlToValidate = this.ID;
_req.ErrorMessage = _errorMessage;
Controls.Add(_req);
base.OnInit(e);
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
base.Render(writer);
_req.RenderControl(writer);
}
}
And here it the ASP.NET page behind:
protected void SubmitClick(object sender, EventArgs e)
{
if(Page.IsValid)
{
// do something
}
}
And here is the ASPX code:
<MyControl:RequiredTextBox runat="server" ErrorMessage="Name is required!" ID="txtName"></MyControl:RequiredTextBox>
<asp:Button ID="Btn_Submit" runat="server" Text="Submit" OnClick="SubmitClick" />
Validators have to inherit from BaseValidator.

Resources