response.write is not working asp.net - c#

On button click event after inserting data I want to show message that data is inserted successfully.
Here is my code
if (com2.ExecuteNonQuery() >= 1)
{
Response.Write("<script LANGUAGE='JavaScript' >alert('Request Submitted Successfully!')</script>");
}
else
{
Response.Write("<script LANGUAGE='JavaScript' >alert('There is some error. Please enter again')</script>");
}
It was working fine until I put code for empty textboxs after insertion in same event soon after above code. here is code
foreach (var control in this.Controls)
{
TextBox tb = control as TextBox;
if (tb != null)
{
tb.Text = string.Empty;
}
}
Response.Redirect("Default.aspx");
now textbox empty after data insertion, data is also inserting but no popup message is showing. Where is problem

I'm not 100% sure on your logic, but instead of having the server perform the redirect, do it on the client side after the call to alert:
if (com2.ExecuteNonQuery() >= 1) {
Response.Write("<script LANGUAGE='JavaScript' >alert('Request Submitted Successfully!');window.location='Default.aspx';</script>");
} else {
Response.Write("<script LANGUAGE='JavaScript' >alert('There is some error. Please enter again');window.location='Default.aspx';</script>");
}

Your Response.Redirect("Default.aspx") is run at the server level so you'll never give the client side a chance to render the javascript and therefore you won't ever see what your Response.Write is outputting.
Why don't you have an <asp:Label> control that will show the message you're looking for.
So, instead of a javascript message you could do:
tb.Text = String.Empty; //clear the textbox
label.Text = "Success Message."; //show the message
It's been awhile since I've used WebForms but this should work if you have Viewstate enabled. You might also want to look into UpdatePanels for this.

Related

Post to facebook group with C# code

I am working on a windows application where I embedded webbroswercontrol. I am trying to post sample message to a open facebook group. I am unable to change value of a textbox with c#. When ever I automate click it says textbox value is null. What would be the fix?
<input type="hidden" autocomplete="off" class="mentionsHidden"
name="xhpc_message" value="lklklkl">
HtmlElement textBox = this.FindControlByName("xhpc_message",
this.webBrowser.Document.All);
//Click Code
var elements = webBrowser.Document.GetElementsByTagName("button");
foreach (HtmlElement element in elements)
{
// If there's more than one button, you can check the
//element.InnerHTML to see if it's the one you want
if (element.InnerText.Contains("Post"))
{
if (textBox.InnerText.Trim() == "Write something...")
{
textBox.Focus();
textBox.GetAttribute("value").Equals("Test Message");
IHTMLElement nativeElement = element.DomElement as IHTMLElement;
nativeElement.click();
break;
}
}
}
1) I suggest you to ensure, that textbox is null, not the textBox.InnerText. Usually inner text for elements is null, so its better to check the "placeholder" attribute and update the code with:
// if (textBox.InnerText.Trim() == "Write something...")
if (textBox.GetAttribute("placeholder") == "Write something...")
2) This code doesn't set the value. It gets the value and compares to "Test message".
textBox.GetAttribute("value").Equals("Test Message");
Just use SetValue instead.
textBox.SetAttribute("value", "Test message");
3) Ensure, that all operations are made after page is loaded.
public SomeFormName()
{
...
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
}
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs args)
{
// put your code here
}
4) Not sure, how the FindControlByName is working, so check a simple LINQ query to ensure that textbox is found.
var textbox = webBrowser.Document.All.OfType<HtmlElement>()
.Where(item => item.Name == "xhpc_message")
.FirstOrDefault()
;
Use the code below after the Document complete event has been fired completely in a separate function, after commenting your code.The URL in the webbrowser should be holding the Group Page on which the post is to happen.
private void AfteDocumentLoads()
{
HtmlElementCollection textBox = webBrowser.Document.GetElementsByTagName("textarea").GetElementsByName("xhpc_message");
HtmlElementCollection button = webBrowser.Document.GetElementsByTagName("button");
foreach (HtmlElement element in textBox)
{
foreach (HtmlElement btnelement in button)
{
if (btnelement.InnerText == "Post")
{
element.Focus();
element.InnerText = txtPortalUserId.Text.ToString();
btnelement.InvokeMember("Click");
}
}
}
}
I was also stuck as it was not posting earlier because I was using WebBrowser class to get current WebBrowser. Result was that the text was inputted to the Group as a 'dim' Comment. Even if I clicked manually on FB page it would say "This status update appears to be blank. Please write something or attach a link or photo to update your status."
I used the page's webbrowser & it worked cos' it came in proper manner on the page. Also little bit of changes are there in the LOCs

How to use an ajax modal popup and consume a value from a link?

I've read a few articles regarding getting values back from a modal popup in an ASP .NET page, but they all seem to use JavaScript to accomplish this which isn't really want I want to do if possible.
I have a web user control which has a repeater that I populate from a list into a table. Each row has a link button which has a redirect url with a value as a query string.
Then I have another web user control which is just a link button with a panel and the repeater web user control that once clicked shows the actual modal popup.
Is it possible to get a value from the web user control once the link button on the repeater is clicked without having to redirect to the same page? I basically want to click on the link, show the modal and once closed, want to access the value.
I'm populating the repeater with the links as follows:
string linkUrl = "";
string action = "";
if (Request.QueryString["action"] != null)
{
action = Request.QueryString["action"];
switch (action)
{
case "SetupCompany":
{
linkUrl = "<a href=CreateCompanies.aspx?companyId=";
break;
}
case "ViewCompany":
{
linkUrl = "<a href=ViewCompany.aspx?companyId=";
break;
}
}
}
CompaniesBusinessManager mgr = new CompaniesBusinessManager();
var companies = mgr.GetCompanies(txtCompanyName.Text, txtRegistrationNumber.Text);
if (linkUrl != "")
{
foreach (var c in companies)
{
c.Name = linkUrl + c.Id.ToString() + "&action=" + action + ">" + c.Name + "</a>";
}
}
rptrCompanies.DataSource = companies;
rptrCompanies.DataBind();
if you don't want the page to be redirected, you will need to use javascript.
There is now way you can pass values from different controls without going back to the server.
In case you keep it without the javascript:
I think you need to pass values from one user control to another. I used to accomplish this by firing reachable events between them.
For example:
in your parent view:
<uc:YourUserControl runat="server" ID="UserControl_Test"
OnYourCustomAction="UserControl_YourUserControl_YourCustomAction" />
In your user control:
public event EventHandler<CustomActionEventArgs> YourCustomAction;
also in the same user control create a public trigger method to be access from others usercontrols
public void TriggerCustomActoinEvent(CustomActionEventArgs EventArgs)
{
if (this.YourCustomAction!= null)
{
this.YourCustomAction(this, EventArgs);
}
}
Hope this help, in on my way to home this was from my mind!
Without a page postback or JavaScript it not really possible. If you are using modal popups you are already using JS, so why not just get the value in JS? You could setup an event handler for all repeater buttons and if they are loaded via ajax use something like this to attach the event handler:
$(document).on('click', '.repeaterButton', function(e) {
var valueOfBtnClicked = $(this).val();
// Do something else
});

jquery function doesn't work when called from usercontrol

I have an aspx page which holds 2 user controls
UC1: Edit page - this has the fields for editing or data entry.
UC2: Notification page - this has a simple message box with jquery function
in my aspx i have this function:
public void ShowMessage(string status, string message)
{
Notification1.Message = message; //this is my user control UC2
Notification1.Status = status;
Notification1.DataBind();
}
now when my aspx page needs to show a message this works fine, but when i want the user control 1 to show a message like (invalid field, or wrong amount) it doesn't do anything. Now it gets called but jquery just doesn't react to it.
in UC2 -notification user control this is what I have:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
<script type="text/javascript">
function showMsg(classname) {
$("#MsgBox").attr('class', classname);
$("#MsgBox").show().delay(5000).fadeOut();
}
</script>
<div id="MsgBox" class="info"><asp:Label ID="lblMessage" runat="server" /></div>
codebehind
public string Status{ get; set; }
public string Message { get; set; }
public override void DataBind()
{
if (Message != string.Empty)
{
lblMessage.Text = Message;
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "showMsg('" + Status + "');", true);
}
}
and this is how i call the function from user control to aspx page:
((myaspxpage)this.Page).ShowMessage("error", "This is my error message.");
any help will be much appreciated! and if further details is needed just let me know.. Thanks in advance.
**EDIT: I tried putting the jquery and message box inside my Edit page to see if it would work that way and it doesn't So it seems that jquery is not working well within a usercontrol??
Move your codes of DataBind() method into OnPreRender. This should work. The reason is that you don't know which code from which step of your page cycle (init, load, bind, ...) is going to change the Message property.
Like in your case it seems you have a button click event where you are setting the Message property from. This is too late because your Notification1 control is already databound.
Leaving it as the latest stage makes it work:
protected override void OnPreRender()
{
if (Message != string.Empty)
{
lblMessage.Text = Message;
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "showMsg('" + Status + "');", true);
}
}
I found the error is what that my button that was calling the function in aspx page was inside an update panel and i needed to add a trigger event to make it work.. Thanks everybody for the help it was that update panel causing the error :(

Using Jquery to prevent a "Submit Button" from posting data if a field is left blank

So I'm putting together a little registration area for my web project, here. The user inputs various strings such as "Username", "Password", etc.
I already have a bit of code set up in order to prevent duplicate Usernames or Passwords in the database. I also have a guard in place if the "Password" and "Repeat Password" fields don't match.
What I'm trying to do now is to -
1: If the user attempts to Submit data while a field is blank, it will not post.
2: Display a "Fields cannot be blank" div I've assigned "display: none" to.
I was thinking something along the lines of assigning the input fields a class of "Required", and using some sort of code such as
if == null
.show;
return false; //To prevent the rest of the function (the submit button posting to login/register) from firing.
Running into obscene problems. Anyway. Here's what I have so far.
$("#SubmitButton").click(function () { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return false; //And nothing else fires
}
$.post("login/register", $('#ConfirmPanel *').serialize(), function (result) {
if (result == 2) //Json return from C#
$("#UsernameInUse").show(); //Shows an error div
else if (result == 3) //Json return from C#
$("#EmailInUse").show(); //Shows an error div
else {
$("#ConfirmPanel").dialog('close'); //Closes the registration dialog
}
});
});
Any thoughts? At first I thought that I literally -cannot- use "class" to mark an input field, and then have that input field compared to a null value. I don't know, though.
You should use the .submit() jquery event handler on the form instead of .click() on the button. Then return false to prevent the normal form submission if needed.
Since you are trying to submit the form using $.post you should stop the default behavior of the form submit by alwasy returning false from submit button click handler.
$("#SubmitButton").click(function () { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return false; //And nothing else fires
}
$.post("login/register", $('#ConfirmPanel *').serialize(), function (result) {
if (result == 2) //Json return from C#
$("#UsernameInUse").show(); //Shows an error div
else if (result == 3) //Json return from C#
$("#EmailInUse").show(); //Shows an error div
else {
$("#ConfirmPanel").dialog('close'); //Closes the registration dialog
}
});
return false;
});
The jQuery way of preventing form submission is to use preventDefault(), like:
$("#SubmitButton").click(function (event) { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
event.preventDefault(); //And nothing else fires
return;
}
//...
});
However, since you are posting the form asynchronously when validation passes, what you really want is something more along the lines of:
$("#SubmitButton").click(function (event) { //Click Submit
event.preventDefault(); //we don't ever want to allow the default behavior
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return;
}
//post the form
});
The rest of what you suggest (using a class to mark each required input field, checking them all for empty strings) is reasonable.
Be aware that because you are binding the button's click event instead of the form's submit event it is entirely possible for the user to submit your form without ever clicking on your button and triggering your validation code. For instance, by pressing return from any one of your text fields.
Also note that in this case you may find it more convenient to just use a traditional onsubmit directive on the form, like:
<form onsubmit="validateAndPost(); return false;">
<!-- inputs and buttons, etc. -->
</form>
<script>
function validateAndPost() {
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return;
}
//post the form
}
</script>
Example: http://jsfiddle.net/AwxGE/
I admire your desire to use jquery, however I would advise using a normal ASP.NET ReqiredFieldValidator control. As well as making your page substantially more concise and easy to maintain, it also allows you to very simply invoke server-side validation:
public void submitbutton_click(object sender, EventArgs args){
Page.Validate();
if(Page.IsValid){
doStuff();
}
}
Please don't reinvent the wheel, and don't trust the browser to behave as you think it will.
use this -
$(document).on('click', '#SubmitButton', function () {
`enter code here`
});

How to validate a duplicate value of textbox in asp.net while submit button

I have 3 text box's and a submit button when i enter the values and submit then values are entered in database .
but when i enter the same values and enter then those values are also entered.......This should not happen...I need a popup window showing there are duplicate values that you have entered.Please give the code for aspx and aspx.cs and data base. Please explain in breif
try
{
int result = Timesheet_BI.InsertCompanyInformation(txtCompanyName.Text, txtAddress.Text);
if (result == -1)
{
txtCompanyName.Focus();
txtCompanyName.Attributes["onfocus"] = "this.select();";
string jv = "<script>alert('Error Details: Duplicate Entry of Company Name ');</script>";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "alert", jv, false);
return;
//Page.ClientScript.RegisterStartupScript(typeof(string), "My Script", "Duplicate Enteries");
}
}
catch (Exception ex)
{
throw ex;
}
Why don;t you use a simple java script to check this.
or
use JQuery /getElementById to get the controls and do a simple comparison.
If you have a bunch of textboxes to compage, give something similar to all the textbox
Eg Give a common prefix to all textbox controls and use JQuery to get all the textboxes starting with that prefix and do a regular comparison.
http://api.jquery.com/attribute-contains-selector/#
Eg;
$(:contains(<prefix>,textbox').each
(
function()
{
// do the comparison
}
)

Categories