i have made a session variable Session["Background1"] = value; in one of my code behind function i want to retrieve this value in my javascript function.
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "SessionValue", "var sessionValue = '" + Session["Background1"] + "';", true);
Personally, I prefer to do it the scripting way. Suppose your variable is currently declared in your Javascript as:
var background1 = null; // TODO: Add value from session.
To add the value from session, all you need to do is this:
var background1 = '<%= Session["Background1"] %>';
When the page is output by ASP.NET, the expression between <%= and %> is evaluated and written to the page, effectively becoming a Response.Write. As long as the member is available in your page at the public or protected level, you can push it into your Javascript it in this way.
I find this approach easier to work with than the obnoxiously verbose ClientScriptManager.
Related
I'm opening a new window to another .aspx page in which I pass a couple of parameters and I wanted to re-pass the parameter ID from the actual page:
<asp:Button ID="Button1" runat="server" CausesValidation="False" meta:resourceKey="btnAddRow2"
OnClientClick="window.open('SecondPage.aspx?type=Usuaris&id=SPECIALID', '_blank')" Text="Miau" />
As you can see, the type parameter works well but I don't have the slightest idea how to get the "specialID" from the current page which would be:
http://blablabla.com/FirstPage.aspx?SPECIALID=36
So i want to get that 36 (which is a dynamic number so I can't actually put a 36 directly over there) in order to open the second page as follows:
http://blablabla.com/SecondPage.aspx?type=Usuaris&SPECIALID=36
As I said at the beginning the user IS at he FirstPage.aspx and upon pressing a button will go to the SecondPage.aspx
hi you can change the OnClientClick to call a javascript function which will get the specialId and then call the window.open with the full string.
for example
function openWindow(){
var specialId = document.getElementById('someElement').value;
window.open('SecondPage.aspx?type=Usuaris&id=' + specialId, '_blank')"
}
I finally could do it doing the following in the FirstPage.aspx:
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
function AddUsuario() {
var id = getParameterByName("id");
window.open('SecondPage.aspx?type=Usuarios&id=' + id, '_blank');
location.reload();
}
On Page_Load() do following
Button1.Attributes.Add("onclick",
String.Format("window.open('SecondPage.aspx?type=Usuaris&id={0}', '_blank');",
Request.QueryString["SPECIALID"]));
In my aspx markup I have the following defined:
<asp:HiddenField runat="server" ClientIDMode="Static" ID="hidField" />
I have C# code as follows, which gives my hidden field a value:
hidField.value = check().ToString();
assume that check is a function which returns true, for simplicity.
I made JS code to do the following:
_myBool = $("#hidField");
alert(_myBool.value);
This alerts undefined.
For debugging purposes, I stepped through and saw that in C#, hidField.value is indeed true.
And I tried alerting _myBool.length which returned 1 and _myBool which returned [Object object] so Im not calling undefined on undefined.
Try this
_myBool = $("#hidField"); //my bool is a jQuery Object
alert(_myBool.val()); //can only get value with .val()
OR
_myBool = $("#hidField")[0]; //[0] gets the element in the object
alert(_myBool.value); //can use the javascript .value
Missing $ symbol..
var _myBool = $("#hidField");
alert(_myBool[0].value); // DOM Object
alert(_myBool.val() ); // jQuery Object
Also note the selector might Not work with runat="server" attribute as it prepends the content placeholder..
This is a better selector
var _myBool = $('[id*="hidField"]');
You forgot the dollarsign and also use the val() function
alert($("#hidField").val());
Make sure you are using the right ID:
_myBool = $("#<%= hidField.ClientID %>").val();
View your source when the page loads and check for that field. Chances are the ID is not "hidField". The code above will be correct.
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.. :)
For a site I'm developing I have two html buttons, not ASP because I do not want them to postback. For the submit button I am calling a javascript function that implements PageMethods to call a C# method from the codebehind. Here is the code for the buttons and the javascript.
<fieldset id="Fieldset">
<button onclick="SendForm();">Send</button>
<button onclick="CancelForm();">Cancel</button>
</fieldset>
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
PageMethods.SendForm(email, OnSucceeded, OnFailed);
}
function OnSucceeded() {
$get("Fieldset").innerHTML = "<p>Thank you!</p>";
}
function OnFailed(error) {
alert(error.get_message());
}
</script>
The codebehind method shown here:
[WebMethod]
public static void SendForm(string email)
{
if (string.IsNullOrEmpty(email))
{
throw new Exception("You must supply an email address.");
}
else
{
if (IsValidEmailAddress(email))
{
bool[] desc = new bool[14];
bool[] local = new bool[14];
bool[] other = new bool[14];
for (int i = 1; i <= 14; i++)
{
desc[i] = ((CheckBox)Page.FindControl("chkDesc" + i.ToString())).Checked;
local[i] = ((CheckBox)Page.FindControl("chkLocal" + i.ToString())).Checked;
other[i] = ((CheckBox)Page.FindControl("chkOther" + i.ToString())).Checked;
/* Do stuff here */
}
}
else
{
throw new Exception("You must supply a valid email address.");
}
}
}
does not work unless it is declared as static. Declaring it as static blocks me from checking the checkboxes on the page because it generates a "An object reference is required for the non-static field, method, or property" error. So my problem can be fixed from either of two directions. A) Is there a way I can have this method work without declaring it as static? B) How do I check the checkboxes if the method is static.
It has to be static, no way around that; But you can access the Page like this
Page page = HttpContext.Current.Handler as Page;
and do FindControl on this page instance.
desc[i] = ((CheckBox)page.FindControl("chkDesc" + i.ToString())).Checked;
Page Methods are a special case of the legacy ASMX web service technology. They allow you to place the service in the codebehind class for the page, and keep you from needing a separate project for the service.
But they will never be able to access anything on the page itself. You'll have to do that from the client side, and pass the values of the check boxes to the service.
If you need to check the checkboxes, then you need to either use an UpdatePanel to do your AJAX stuff, or return something from your page method (ideally a string) and check the checkboxes based on what's returned in javascript on client.
I have application like where i can create dynamic tabs. and delete cross bar option on tabs. When I am trying to delete the tab I am getting error like
Microsoft JScript runtime error: 'null' is null or not an object and point to my Javascript code.
Here is my JS code.
<script type="text/javascript">
/* <![CDATA[ */
function deleteTab(tabText)
{
var tabStrip = $find("<%= RadTabStrip1.ClientID %>");
var multiPage = $find("<%= RadMultiPage1.ClientID %>");
var tab = tabStrip.findTabByText(tabText);
var pageView = tab.get_pageView();
var tabToSelect = tab.get_nextTab();
if (!tabToSelect)
tabToSelect = tab.get_previousTab();
tabStrip.get_tabs().remove(tab);
multiPage.get_pageViews().remove(pageView);
if (tabToSelect)
tabToSelect.set_selected(true);
}
/* ]]> */
</script>
and in page lode
if (!Page.IsPostBack)
{
RadTab tab = new RadTab();
tab.Text = string.Format("New Page {0}", 1);
RadTabStrip1.Tabs.Add(tab);
RadPageView pageView = new RadPageView();
pageView.Height = new Unit("50px");
pageView.Width = new Unit("1300px");
RadMultiPage1.PageViews.Add(pageView);
BuildPageViewContents(pageView, RadTabStrip1.Tabs.Count);
RadTabStrip1.SelectedIndex = 0;
}
This error can occur if you are trying to use an object which is null. In that code quite a lot of things can return null: $find, findTabByText, getPageView, get_nextTab, get_previousTab etc. I suggest you alert() everything before using it. That way you will find what is null.
You're not checking any of those function calls to see if they're actually returning something. One of them is returning null, but your code does not notice that and tries to use the result in a subsequent statement.
Try this in Firefox with Firebug and you'll probably get better error messages.
$find can return null if you are trying to call it too early. Remember that ASP.NET AJAX controls are created during the Sys.Application.Init event. If you try to access them earlier (e.g. in the window.onload) the $find() will not work.