Show Asp.Net Page By Using Javascript - c#

Is it possible in javascript to open new aspx page by using javascript?.
I mean if I wants to open a new page in asp.net than I will use "Server.Transfer" method to open new aspx page the same thing I am asking over here to open new aspx page by using javascript.
Is it possible?.
I am trying as per your suggestion as below:
<script type="text/javascript">
$(document).ready(function()
{
function kpr(e)
{
if(e.which==17 && e.which==18 && e.which==82 || e.keyCode==17 && e.keyCode==18 && e.keyCode==82)
{
window.location.href="MemberInfo.aspx";
}
}
});
</script>
but it not allowed me to show new page as above........

Something like this (in the appropriate point in your script):
window.location.href = "OtherPage.aspx"

Try this in your client side function:
window.location.assign("Page.aspx")

Try using the debugging tools of your browser and set a checkpoint in your function to make sure that it actually gets to the window.location.href line.

Related

Razor server side code block and Jquery

My application is MVC5 c#, trying to execute the following:
#{
var s = Model.PhysicalExam;
if (s == null)
{
<script>
alert("1");
$("#newSale1").hide();
</script>
}
else
{
<script>
alert("2");
$("#newSale1").show();
</script>
}
}
Alert works, however does not hide or show the button. Would appreciate your suggestions.
I would guess that newSale1 maybe isn't loaded in the DOM when that script code is executed. You should probably put those blocks inside a document ready event.
$( document ).ready(function() {
console.log( "ready!" );
});
I might go with something like this at the bottom of the page
<script type='text/javascript">
var isExamNull = #((Model.PhysicalExam == null).ToString());
$(document).ready( function(){
if (isExamNull)
$("#newSale1").hide();
else
$("#newSale1").show();
};)
</script>
Putting scripts at the bottom of the page lets the html render first, $(document).ready ensure that, well, the document is ready. Using the #() will write your server side values into your scripts, another technique is to use a hidden and have the script check the value of the hidden.

Variable from javascript function in aspx page accessible in c# code in same javascript function

My code in aspx page is:
<script type="text/javascript">
function MenuItem_Click(itemId) {
<%
MyAspLogger("Clicked on item: {0}", itemId);
%>
}
</script>
I don't know how to access "itemId". I know that from other side - accessing c# variable in aspx code it is possible. But I don't know if is possible access javascript variable in c# code include in same javascript function.
Thank you for your help.
I guess you are tryingto get the clicked menu ids, and then log all clicked menu item?
1- To get the menu id,
Pass the menu object using keyword "this" to the function handling the click (MenuItem_Click).
<a id='menu_1 onclick='return MenuItem_Click(this);'>Click Me!</a>
<script type="text/javascript">
function MenuItem_Click(me) {
alert(me.id); // The Id of menu clicked.
// Do Whatever you want with the id now.
.
.
.
}
</script>
2- Logging clicked menu id
You have 2 options actually ... use a web-service call each time a menu clicked (which I don't recommend)
OR
Use a variable to store the clicked menu ids Or a hidden variable.
<script type="text/javascript">
function MenuItem_Click(me) {
var hdnMenuLog = document.getElementById('hdnMenuLog');
hdnMenuLog.value = hdnMenuLog.value + '|' + me.id;
}
</script>
Hope this helps!
You can not access javascript variable value in server side code until you do postback and send asnc call using ajax. Asp.net generates html and javascript code from server side and sends response to client i.e. browser.
To access javascript variable value after postback you can assign it to some hidden field that is made server accessible and access it on server side code. This is how asp.net maintains ViewState.
I tried
<asp:Label CssClass="helperLabel" runat="server" Visible="False">Test</asp:Label>
<script type="text/javascript">
function MenuItem_Click(item) {
// Setup
$(".helperLabel").html("asdf");
<%
MyAspLogger("Clicked on item");
%>
</script>
in code behind I have
protected void MyAspLogger(string logMessage)
{
MyLogger.Debug(logMessage + "/" + helperLabelId.Text);
}
It's working fine but 2 other issue.
Text is not change on server side but only on client side(saw that after removed Visible attribute from asp control).
And also I found that MyAspLogger method is called on page load not after click event.
What I need is grabb itemId and log that via my Logger method from code behind.
Thank you.

Add CSS and JS in AJAX-loaded PartialView

I found many answers about similar topics but all refers to PartialViews loaded not by AJAX where solutions are e.g. HtmlHelpers or Head section, but it doesn't work when I load PartialView by AJAX.
I wanna add CSS stylesheet and JS script inside AJAX-loaded PartialView. Now I coded it inside PartialView and it works but it's not good solution (include scripts and stylesheets inside body).
Everything should work just fine except validation. You need to tell jQuery about your new content on order to validate it.
See
ASP.Net MVC: Can you use Data Annotations / Validation with an AJAX / jQuery call?
If you are only loading the PartialView once onto the page, there should be no problem including the scripts and CSS in the body. Like Adam said if you are including a HTML Form dynamically you just have to tell jQuery about it see here ASP.Net MVC 3 client side validation with a dynamic form
However if you want to include the same PartialView multiple times on to the page and do not want to load the script multiple times. Then there are dynamic script loaders you can use that:
You can call just one from your main page, when you load the AJAX so that it is only included once
Include a check to make sure the same script is not loaded multiple times.
I didn't know that earlier that using script tag inside body is not evil. So it's not that bad I thought at first.
I implemented two functions in cssLink.js which I include in head:
/// <reference path="../jquery-1.4.4.js" />
function addCssLink(link) {
var _cssLink = '<link rel=\"stylesheet\" href=\"' + link + '\" type=\"text/css\" />';
$head = $('head');
$link = $('link[href=' + link + ']', $head);
if ($link.length == 0) {
$head.append(_cssLink);
}
}
function removeCssLink(link) {
$('head link[href=' + link + ']').remove();
}
and I use those functions within PartialViews:
<script type="text/javascript">
$(document).ready(function () {
$('#sideMenu').tabs('#content', '#content > *');
addCssLink('/Content/SideMenu.css');
});
</script>
<script type="text/javascript">
$(document).ready(function () {
removeCssLink('/Content/SideMenu.css');
});
</script>
Thank you guys for help, I think that informations about validation should be helpful for me later :)

Referencing the ASP.NET web control in javascript

I have created a drop down list in my user control, see source code below,
<asp:DropDownList ID="ddlInd" runat="server" DataSourceID="indXmlDS" DataTextField="text" DataValueField="text"></asp:DropDownList>
In Page_load I have done this:
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(this.GetType(), "myScript", "<script language='javascript' src='../Scripts/myJS.js'></script>");
ddlInd.Attributes["onchange"] = "showTextbox()";
}
So what code should I be using, if I would like to refer to this control in my external javascript file, myJS.js?
I have tried to use document.getElementById("<%=ddlInd.ClientID %>") but it would return NULL.
Can anyone help? Thanks
EDIT:
Not sure if attaching that myJS.js file would be helpful here
function showTextbox() {
var sid = <%=ddlInd.ClientID %>;
//alert(sid);
var s = document.getElementById('<%=ddlInd.ClientID %>'); // <-- problem here
alert(s);
if (s.options[s.selectedIndex].value == "Other") {
myDiv.style.display = "inline";
alert("display");
}
else {
myDiv.style.display = "none";
alert("none");
}
}
EDIT2:
I kinda found the workaround which is to embed scripts in the user control page instead of using external script file. Thanks for the suggestions everyone. They were all very helpful.
Also the modified js script is as follows, and it works:
function showTextbox(objID) {
var s = document.getElementById(objID);
var div = document.getElementById("myDiv");
if (s.options[s.selectedIndex].value == "Other") {
div.style.display = "inline";
}
else {
div.style.display = "none";
}
}
Try using ClientScriptManager.RegisterClientScriptInclude instead of RegisterStartupScript.
It seems in your case you're including an external javascript file, rather than javascript code that should directly appear in the page.
Also try changing the double quotes " to single quotes ' in document.getElementById('<%=ddlInd.ClientID %>')
EDIT oh, I see that you're trying to do <%=ddlIndustry.ClientID %> inside your javascript file. That is not going to be interpreted in an external js file! You should either include your function directly in teh page (not as an external file) or try to pass the ColntrolId as an argument to the js function
Try to set the ClientIdMode of the control to Predictable:
<asp:DropDownList ID="ddlInd" ClientIDMode="Predictable" runat="server" DataSourceID="indXmlDS" DataTextField="text" DataValueField="text"></asp:DropDownList>
You can also use a static ClientId by using ClientIDMode="Static" in which case the ClientId will be equal to the id of the control, so you can say:
document.getElementById("ddlInd");
you could use this to reference your control to .js file
$('select#ddlInd').val(....)
if the dropdownlist is inside a "ContentPlaceholder", you could do this
$('select#ContentPlaceholderID_ddlInd').val(...)
place it in your .js file
Note : include of course your .js file
If you can't use .NET 4.0 and are stuck on 3.5/2.0, I wrote a small library called Awesome.ClientID to solve this problem.
I've posted it before in this answer: How do I make this getElementsbyName work for IE (and FF)?
Basically it will allow you to serialize all your controls to a JSON array, and you can change your JavaScript to:
document.getElementById(controls.ddlInd);
The library can be found here: http://awesomeclientid.codeplex.com/
Blog post about it: http://www.philliphaydon.com/2010/12/i-love-clean-client-ids-especially-with-net-2-0/
You can use <%=Control.ClientID %> When you have script on the .aspx page if your using an External file then u have to use the control id <%=ddlInd.ClientID %> will not work.

asp.net Refresh base page from iframe

I have page with other asp.net page inside iframe.
And on button click inside iframe i need to refresh main page from server side.
How can it?
Make use of javascript and you can easily do it
call the following function on your button click
<script language="javascript">
function RefreshParent()
{
window.parent.location.href = window.parent.location.href;
}
</script>
From the cs code if you are opening the aspx page in the iframe
Page.RegisterStartupScript("RefreshParent","<script
language='javascript'>RefreshParent()</script>");
Its explained very well in the following links:
link 1
link 2
Hope it helps.
For some reason the javascript function shown in earlier answers did not work for me (although the function was called). However, this worked for me:
function RefreshParent()
{
// Was: window.parent.location.href = window.parent.location.href;
parent.location.reload();
}
I had to add it near the start of my HTML (near the end of the HTML didn't work, as it was not yet rendered).
I used this C# code to call it, which is based on earlier answers but updated to use the current API which has an extra initial paramter, "type":
ClientScript.RegisterStartupScript(this.GetType(), "RefreshParent", "<script language='javascript'>RefreshParent()</script>");

Categories

Resources