Here's the deal. Have a functioning web app using ASP.NET WebForms with a C# backend. The thing works fine, but I'm always looking to improve, as a beginner at this stuff. Right now, to deal with a user's search coming back with no results, I utilize the following, and was wondering if there was any cleaner way to do it, for future reference:
DataClass data = new DataClass();
var searchresults = data.GetData(searchBox.Text);
int datanumber = searchresults.Count();
if (datanumber == 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "javascript:alert('There were no records found to match your search');", true);
}
else
{
DropDownList1.Visible = true;
DropDownList1.Items.Clear();
DropDownList1.DataSource = searchresults;
DropDownList1.DataBind();
}
I agree with the not using popups, so you could always do something as simple as having a Label object on your page:
<asp:Label runat="server" id="lblResultMsg" ForeColor="Red" Visible="False" />
And then set the text dynamically (or add it as a property to the code) and set the label to be visible on postback if no results are found:
if (datanumber == 0)
{
lblResultMsg.Text = "There were no records found to match your search.";
lblResultMsg.Visible = true;
}
else
{
lblResultMsg.Text = "";
lblResultMsg.Visible = false;
// do your data binding
}
But there are quite a vast number of ways you could achieve something like this. Regarding your question about using the .Count from the Enumerable collection - there's nothing stopping you doing this as it's perfectly valid. The question is which method do you find more readable?
if you include the jquery ui dialog (http://jqueryui.com/demos/dialog/), you can simply call this to create a nice dialog box:
$('<div>message</div>').dialog({autoOpen:true,title:'Error'});
Personally I prefer to create a helper function for inserting the relevant javascript into the page, and only pass parameters to the function so that I don't need to worry about the messy details every time.
Something like :
public static void GrowlMessage(System.Web.UI.Control pageControl, string header = "", string message = "", bool sticky = false, string position = "top-right", string theme = "", bool closer = true, int life = 8)
{
string _js = "$.jGrowl('" + HttpContext.Current.Server.HtmlEncode(message) + "', { header:'" + header + "', sticky:" + sticky.ToString().ToLower() + ", position: '" + position + "', theme: '" + theme + "', closer: " + closer.ToString().ToLower() + ", life:" + life * 1000 + "});";
ScriptManager.RegisterStartupScript(pageControl, pageControl.GetType(),"Growl",_js, true);
}
The sample I have used also requires jQuery and the jGrowl library available here. And IMHO the messages are pretty. They are unobtrusive, the user does not need to click a button to make them go away, and they fade away after your specified amount of time.
But I agree with Mike, that if you don't have any records, you should just use the built in properties of a GridView (EmptyDataRowStyle and EmptyDataRowText) to display a 'no data matching your query' style message. Assuming that you're using a GridView at all, that is..
When it comes to user feedback, Impromptu is my friend. There is a nice ASP.NET implementation of Impromptu on Aaron Goldenthal's website: http://www.aarongoldenthal.com/post/2009/11/11/Using-jQuery-Impromptu-With-ASPNET.aspx
If you have decided to alert user via alert then please go ahead with light box effect..
http://www.designyourway.net/blog/resources/30-efficient-jquery-lightbox-plugins/
if you are still would like to go ahead with traditional alert then obviously its easy for you to fire it up on page load rather than attaching script to it..
')" ....>
Because if you require any change then you just need to alter the javascript alone and you dont need to build project again to test it...
Hope its useful for you..
Note: I'm using my own DLLs to render content so above coding may requires alteration because i did forget traditional asp codings.. :)
Related
I have a text field that contains a 2 digit value by default. I want to clear it before I type a new value. I was using TextSlider.Clear(); but after the latest ChromeDriver update, it's no longer working so I am trying to workaround it using backspace. Currently I am doing two backspaces, one at a time.
TextSlider.SendKeys(Keys.Backspace);
TextSlider.SendKeys(Keys.Backspace);
I also tried DELETE but that's also not working. Is there any way to do this in a single line?
Thank you all,
i have managed to workaround using ctrl A and Delete
TextSlider.SendKeys(Keys.Control + "a");
TextSlider.SendKeys(Keys.Delete);
TextSlider.SendKeys(Keys.Backspace + Keys.Backspace);
First try to fix like how TextSlider.Clear(); is not working. There might me loading issue, SendKeys method will work. Try to add wait for page to load properly.
If still not working then you can use,
TextSlider.Click();
TextSlider.Clear();
But below functionality will definatly work,
TextSlider.SendKeys(Keys.Backspace + Keys.Backspace);
Instead of using Keys.Backspace, ideally to clear a text field you need to induce WebDriverWait for the element to be clickable and you can use either of the following solutions:
Using ElementToBeClickable Method (IWebElement):
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(TextSlider)).Clear();
Using ElementToBeClickable Method (By):
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(By.CssSelector("css_TextSlider")).Clear();
Another option is to clear the text element by using Javascript. Due to issues occurring in certain parallel testing situations, I stopped relying on the SendKeys function some time ago. Instead, I use these functions now to set a certain text:
private void SetText(IWebElement element, string text, bool clearOldText)
{
// Clear old text if needed
if (clearOldText)
{
LogInfo("Clearing " + element.ToString() + #" from any text.");
SetElementValue(element, "");
}
element.Click();
SetElementValue(element, text);
}
public string SetElementValue(IWebElement element, string value)
{
ScrollToElement(element);
PaintElement(element, "yellow");
var exec = (IJavaScriptExecutor)this;
var script = #"
var el = arguments[0];
el.value = '" + value + #"';
try
{
if (""createEvent"" in document) {
var evt = document.createEvent(""HTMLEvents"");
evt.initEvent(""change"", false, true);
el.dispatchEvent(evt);
}
else
el.fireEvent(""onchange"");
}
catch(err){ return err; }
return ""Javascript executed."";
";
LogInfo("Setting value to '" + value + "' for " + element.ToString());
var result = exec.ExecuteScript(script, element);
Recorder?.AddScreenshot();
return result.ToString();
}
Personally I dislike the hardcoded javascript a bit, but it always did the job reliably. "SetElementValue" is called twice in this code to ensure correct handling of certain events in my tests: it might not be necessary in other cases.
So, I am dynamically generating jQuery using C# and sending it to the webpage.
The problem is it appears to be generating correct jQuery according to the file and according to Js Fiddle but it does not actually work on the page.
The jsFiddle is here http://jsfiddle.net/ER2hE/
Now I looked up how to send javacript to the website. It should work like this.
http://msdn.microsoft.com/en-us/library/bb359558.aspx
and my code which does that is this method
private void sendScript(string script)
{
const string someScript = "alertMe";
//send the built script to the website.
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), someScript, script, true);
}
This is super simple it has worked for other pieces of code calling. But it has not for this instance.
The code that calls it is this in my C#
private void populateGroups()
{
//this generates correct javascript according to the file and JS fiddle but unfortunately doees not work.
string splitme = "USE ACES SELECT GroupName, GroupID FROM PrimaryGroup ORDER BY GroupName";
DataTable dt = fillDataTable(splitme);
string script = "";
foreach (DataRow dr in dt.Rows)
{
//add the locations to the <select> box
script += " $('#groupList').append('<option value=\" " + dr.ItemArray[1].ToString() + " \"> " + dr.ItemArray[0].ToString() + " </option>'); ";
}
sendScript(script);
JSErrorLog(script, "GROUPS");
}
The whole thing is being called on startup
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
populateMakes();
populateLocation();
populateGroups();
}
}
The jQuery its generating also works in JSFiddle I am pulling this from a method that writes the javascript it generates in a method calling here is the fiddle JSErrorLog.
http://jsfiddle.net/ER2hE/
Oh and my html in my aspx file looks like this
<div class="row2">
<span>Group</span>
<select id="groupList" multiple="multiple" onclick="setGroups()" class="normalsize">
</select>
</div>
I believe that is everything. I just want my stuff to work. I am willing to post any additional code, just ask. If you have an idea as to why its not working, let me know.
When does it actually execute that code? Before or after the element with id "groupList" exists in the DOM? My guess is before.
Solution? Wrap your code inside a document.ready handler.
jQuery(function($) {
$('#groupList').append('<option value=" 46 "> AC Units </option>');
// etc etc
});
Return simple string js code. And run it with eval()
In my application I'm showing a javascript pop up with a web page in it with the help of the following code:
popwin = window.open(URL, '" + id + "',
'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=750,
height=600,left = 262,top = 84');
which is giving me the required pop up with the web page in it.
I want to know whether there is any way to remove user interaction from this pop up and to remove the close button as well.
I will close this pop up using some timer ,but i don't want that user to be able to control the pop up. Is there any way for it?
I googled a bit but haven't got the relevant way to do it.
Note: Can i do this using Modal Pop Up?
Please suggest any good ways .
You can try following code.
popwin = window.open(URL, '" + id + "','toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=750, height=600,left = 262,top = 84');
SetTimeOut(function(){ popwin.close()},2000);
Here '2000' is time in milliseconds. 2000 ms = 2sec.
Let me know if any error occurs.
You can try Telerik Radwindows.
You can load your content in a Fancy Box and customize the fancybox as per your needs.
I think it could be more appropriate to use a CSS-like popup instead.
Working example:
http://www.pat-burt.com/csspopup.html#
As for your timer you could change the css attribute with your timer or use some jquery framework plugin like impromptu:
http://trentrichardson.com/Impromptu/
Which cost less time to deploy than the css solution I think.
hey man this is my popup. its not a window but acts like a window and is in jquery and javascript both.
$("document").ready( function() {
var link = ""; // your link here
var d = document.createElement("div");
d.style.display = "block";
d.style.border = "1px solid #282828";
d.style.background = "#ffffff";
d.style.width = "750px";
d.style.height = "450px";
d.setAttribute("id", "popup");
var m = document.createElement("iframe");
m.setAttribute("src", link);
m.style.width = "750px";
m.style.height = "450px";
m.style.border = "0";
document.body.appendChild(d);
d.appendChild(m);
var s=0;
var n = setInterval( function() { s=s+1; if (s == 5) {
$("#popup").remove();
} }, 1000);
});
http://jsfiddle.net/APKTX/
Im made a webform that insert data to the database. When the insert button was clicked, the codes for inserting data is triggered and after successfully inserting data, It redirects to other page that says "Data Inserted Successfully".
It was like this...
INSERT PAGE.....
if (CodeClass.InsertData(txtFirstName.Text, txtLastName.Text, Gender) == true)
{
String A = "InsertSuccess";
Response.Redirect("OtherPage.aspx?&lnk=" + A);
}
OTHER PAGE....
String link = null;
link = Request.QueryString["lnk"];
if (link == "InsertSuccess")
{
txtLabel.Text = "Record inserted succesfully!";
}
My problem is when I access the OTHER PAGE even I did not use the insert page..I am getting same results. Lets say I typed ..http://localhost:8672/OtherPage.aspx?&lnk=InsertSuccess in the address bar..I am getting "Record inserted succesfully!" label. I want the OTHER PAGE to never show "Record inserted succesfully!" message when I actually did not insert something but rather just access it through the browser's address bar.
you may use Session variable to store updated status and then check if it is available in otherpage.aspx,update textbox and reset it.
Insert Page
if (CodeClass.InsertData(txtFirstName.Text, txtLastName.Text, Gender) == true)
{
Session["status"]="InsertSuccess";
Response.Redirect("OtherPage.aspx");
}
}
Other Page
if (Session["status"]!=null)
{
txtLabel.Text = "Record inserted succesfully!";
Session["status"]=null;
}
Well for what I see you dont want to get the message just by typing "http://localhost:8672/OtherPage.aspx&lnk=InsertSuccess" in the address bar, then I would recommend you that instead of passing a string with a flag you should pass the record ID, then on your other page you should check that your record ID really exist on your table.
For that I hope that you are working with ID as a GUID type.
You'll have something like this:
"http://localhost:8672/OtherPage.aspx&lnk=BBB5259E-F5A3-4271-ABC8-D95A00BE9770"
Otherwise it would be too easy to remember an int ID.
if (CodeClass.InsertData(txtFirstName.Text, txtLastName.Text, Gender) == true)
{
HttpContext.Current.Items["A"]= "Inserted Successfully";
Server.Transfer("OtherPage.aspx);
}
string ContextData =(string) HttpContext.Current.Items["A"];
if(!string.Empty(ContextData))
{
Label1.Text = ContextData;
}
Assuming you fix your URL and remove the "&" after the "?" .. You have to remove the "&"
Have you thought about the browser cache? sometimes cache can do this and I have struggled with an issue similar to yours because of the cache settings.
You should change your querystring.
Response.Redirect("OtherPage.aspx?&lnk=" + A);
Should be:
Response.Redirect("OtherPage.aspx?lnk=" + A);
The '&' sign when not encoded are treated as a parameter separator.
Response.Redirect("OtherPage.aspx?lnk=" + A + "&secondParam=someValue");
As requested by comment:See this SO post
MSDN HttpServerUtility.UrlEncode
.NET Slave - Working with query strings
and the String.IsNullOrWhiteSpace() might be handy sometimes.
Just add this script after succeed inserted code:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success", "setInterval(function(){location.href='Default.aspx';},3000);", true);
So I need to pass to a JavaScript function an array of strings in my view based on data from the database. So I have this code in the controller:
string top_six_string = "[";
foreach (ObjectModel om in collection)
{
myProject.Models.BlobFile file = null;
if (om.BlobFile != null)
{
file = om.BlobFile;
}
else if (om.BlobFiles.Count != 0)
{
file = om.BlobFiles.First();
}
if (file != null)
{
top_six_string += " \"" + file.BlobFileID + "\",";
}
}
top_six_string = top_six_string.TrimEnd(',');
top_six_string += "]";
ViewBag.TopSixList = top_six_string;
Now, I don't particularly understand why we have both a BlobFile field and a BlobFiles collection, but that's not that point. The point is, debugging shows that I accurately the get the string I want (of the form ["25", "21", "61", "59"]).
But when running the JavaScript, I got the confusing error "Unexpected character &", and a little source-viewing in Chrome led me to learn that the string came out looking like this:
[ "25", "21", "61", "59"]
So my assumption is that the ViewBag is sanitizing string that it is passed for display in HTML, but obviously that isn't my concern right now. Am I correct in my assumption? Is there another way to pass the view this information? Is there a way I can coerce the string back to quotes afterwards?
The problem is most likely when you output the contents of the ViewBag in your View. By default the Html helpers sanitize output to help protect against injection attacks.
What you want is this when outputting the value in your View: #Html.Raw(ViewBag.TopSixList)
Since programmers barely use MVC3 and google shows this page also for Asp core
In ASP.Net Core change this line :
ViewBag.TopSixList = top_six_string;
To
ViewBag.TopSixList = new HtmlString(top_six_string);
And add using Microsoft.AspNetCore.Html; if HtmlString is not accessible.