Assign href of anchor tag - javascript

I want to assign href of Anchor tag using JavaScript.
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="AnchorTRY.aspx.cs" Inherits="AnchorTRY" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<a id="anchr" runat="server"> </a>
<script type="text/javascript">
if (System.Web.HttpContext.Current.Session["Email"] == null && System.Web.HttpContext.Current.Session["uid"] == null)
{
document.getElementById("anchr").setAttribute('href', "User Login.aspx");
document.getElementById("anchr").innerText = "Create Your Own Package";
}
else {
document.getElementById("anchr").setAttribute('href', "Cities.aspx");
document.getElementById("anchr").innerText = "Add to Your Package";
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
</asp:Content>

Change you code to this,
<script type="text/javascript">
function setHref() {
var flag = <%
if (System.Web.HttpContext.Current.Session["Email"] == null && System.Web.HttpContext.Current.Session["uid"] == null)
{
response.write("true");
}
else
{
response.write("false");
}
%>;
if(flag == true)
{
document.getElementById("anchr").setAttribute('href', "User Login.aspx");
document.getElementById("anchr").innerText = "Create Your Own Package";
}
else {
document.getElementById("anchr").setAttribute('href', "Cities.aspx");
document.getElementById("anchr").innerText = "Add to Your Package";
}
}
</script>
In the code we are assigning the output of your server-side code to a JavaScript variable 'flag' and according to its value JavaScript code will assign the href attribute.
And we have placed this code in to a JavaScript function, we will call it when document loads, so that it will change 'href' of anchor properly otherwise the code couldn't access anchor tag before it loads.
Call the function in body tag like this,
<body onload="setHref();">
Hope it works, let me know if you want more help. Thank you.

<a href="Index/MasterPage?modID=<%=Session["ProductID"]%> ">
can use like this directly we can assign session values to href

Related

Java List element is undefined inside anchor tag

There is a list defined as:
List<String> list = Arrays.asList("Abc", "Def");
The problem is inside anchor tag the list element is coming as undefined.
for (int i = 0; i < list.size(); i++) {
<a id="<%=list.get(i)%>" href="javascript:;" onClick="openWindow(<%=list.get(i)%>);" align="left">Proceed</a>
}
The openWindow function is defined as below:
function OpenHierarchyWindow(id) {
alert("id value "+id.value);
}
The alert function is giving output as undefined. Why the list.get(i) is unable to fetch the data inside the anchor tag.
here JSP scriplets inside onClick javascript function should be quoted.
You can replace
onClick="openWindow(<%=list.get(i)%>);"
With
onClick="openWindow('<%=list.get(i)%>');"
Below is complete code for the same.
<%# page import="java.util.List"%>
<%# page import="java.util.Arrays"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Scriplets And Java Script</title>
<script type="text/javascript">
function OpenHierarchyWindow(id) {
alert("id value " + id);
}
</script>
</head>
<body>
<%
List<String> list = Arrays.asList("Abc", "Def");
for (int i = 0; i < list.size(); i++) {%>
<a id="<%=list.get(i)%>" href="javascript:;" onClick="OpenHierarchyWindow('<%=list.get(i)%>');" align="left">Proceed</a>
<%}%>
</body>
</html>

When Ext.Net App.direct is defined?

I have a problem using Ext.Net 2.5 and App.Direct:
Ext.onReady(function() {
App.direct.GetAll({
success: function (result) {
currentMessageId = result;
}
});
});
The problem exist in body onload too.
When I Call the direct method in Ext.onReady it gives me this error: "Cannot Call GetAll of undefined."
But, when I call it instead a click button handler it works without problem.
So, the question is:
When App.direct is defined?
In the Page Sources you could see the following.
Ext.onReady(function () {
Ext.ns("App.direct");
Ext.apply(App.direct, {
TestDirectMethod: function (config) {
return Ext.net.DirectMethod.request("TestDirectMethod", Ext.applyIf(config || {}, {}));
}
});
});
It is how a DirectMethod is rendered to a browser.
As you can see it is inside an Ext.onReady function. So, your onReady function is executed before that.
You can force rendering of our onReady function before your one using a ResourcePlaceHolder.
<%# Page Language="C#" %>
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<script runat="server">
[DirectMethod]
public void TestDirectMethod()
{
X.Msg.Alert("DirectMethod", "Hello from Server!").Show();
}
</script>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Ext.NET v2 Example</title>
<ext:ResourcePlaceHolder runat="server" Mode="Script" />
<script>
Ext.onReady(function() {
App.direct.TestDirectMethod();
});
</script>
</head>
<body>
<form runat="server">
<ext:ResourceManager runat="server" />
</form>
</body>
</html>
Here is a description of possible options for a ResourcePlaceHolder's Mode.

Getting session value in javascript

I am using an external javascript file for my asp.net project. Now i want to get the session value in that javascript. How can i get the session value in that javascript file?
Thanks in advance..
<script>
var someSession = '<%= Session["SessionName"].ToString() %>';
alert(someSession)
</script>
This code you can write in Aspx. If you want this in some js.file, you have two ways:
Make aspx file which writes complete JS code, and set source of this file as Script src
Make handler, to process JS file as aspx.
You can access your session variable like '<%= Session["VariableName"]%>'
the text in single quotes will give session value.
1)
<script>
var session ='<%= Session["VariableName"]%>'
</script>
2) you can take a hidden field and assign value at server;
hiddenfield.value= session["xyz"].tostring();
//and in script you access the hiddenfield like
alert(document.getElementbyId("hiddenfield").value);
For me this code worked in JavaScript like a charm!
<%= session.getAttribute("variableName")%>
hope it helps...
I tried following with ASP.NET MVC 5, its works for me
var sessionData = "#Session["SessionName"]";
protected void Page_Load(object sender, EventArgs e)
{
Session["MyTest"] = "abcd";
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
if (TextBox1.Text.Equals("")) { }
else {
Session["MyTest"] = TextBox1.Text;
}
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script language=javascript type="text/javascript">
function getMyvalSession() {
var txt = "efgh";
var ff = '<%=Session["MyTest"] %>' + txt;
return ff ;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack=true ></asp:TextBox>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".
Example for VB:
<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>
var sessionVal = '#Session["EnergyUnit"]';
alert(sessionVal);

Current context value is not rendered from Usercontrol to .aspx page

i have default.aspx page and one user control.
usercontrol is having following code for multiple file uploads.
now the problem is when i add a file for upload that current context file is not giving me any value it is still zero i guess because it is rendering from user control.
what should i do?
My Usercontrol UPLOAD.ASCX
<%# Control Language="C#" AutoEventWireup="true" CodeFile="FileUpload.ascx.cs" Inherits="FileUpload" %>
<script type="text/javascript" src="_scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
var i = 1;
$(document).ready(function () {
$("#addfile").click(function () {
$("#dvfiles").append("<input name=" + i + "fu type=file /><a href=#>remove</a><br>");
i++;
});
$("#dvfiles a").live('click', function () {
$(this).prev("input[type=file]").remove();
$(this).remove();
});
});
$(document).submit(function () {
var flag = true;
$("#dvfiles input[type=file]").each(function () {
if ($(this).val() == "") {
$(this).css("background", "Red");
flag = false;
}
});
return flag;
});
</script>
<div id="Fileuploader">
Attach a file..<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
onclick="btnUpload_Click" />
</div>
UPLOAD.ASCX.CS
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
HttpFileCollection filecolln = Request.Files;
//here i don't get values of current files.
// this is zero. because of this following if condition failed
//please help here
if (filecolln.Count > 0)
{
for (int i = 0; i < filecolln.Count; i++)
{
HttpPostedFile file = filecolln[i];
if (file.ContentLength > 0)
{
file.SaveAs(ConfigurationManager.AppSettings["FilePath"] + System.IO.Path.GetFileName(file.FileName));
}
}
lblMessage.Text = "Uploaded Successfully!";
}
else
{
lblMessage.Text = "No files selected!";
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
Default.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<%# Register TagPrefix="ucFileuploader" tagName="Fileuploader" src="FileUpload.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<ucFileuploader:Fileuploader ID="Fileuploder" runat="server" />
</div>
</form>
</body>
</html>
The problem is that you are using javascript an id names.
so when you have control with id addfile in .aspx it is rendered as is,
but when you have control with id addfile in user control with id Fileuploader,
than the rendered id is Fileuploader_addfile,
so change id name in java script with the proper id.
To chechk what is name of rendered id, open page in browser, open source of the page and find you element and copy id into java script.
Change all ids in java script with rendered id names.
I would suspect it could be this line:
<script type="text/javascript" src="_scripts/jquery-1.4.1.min.js"></script>
Which should be:
<script type="text/javascript" src="/_scripts/jquery-1.4.1.min.js"></script>

JavaScript on jQuery created code never gets called

This is my view in ASP.NET MVC.
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Administration.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="HeadContent" runat="server">
<script type="text/javascript">
var ddlContentTypes;
$(document).ready(function () {
ddlContentTypes = $("#ContentTypes");
ddlContentTypes.bind("change", loadCreate);
loadCreate();
});
function loadCreate() {
var typeId = $("#ContentTypes option:selected").val();
$.get('~/' + typeId + '/Create', function (data) {
$("#CreateForm").html(data);
});
$("fieldset input").each(function (index, item) {
$(item).attr("disabled", true);
});
}
</script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<h2>
<%=Resources.Localize.CreateWidget %></h2>
<p>
<% Html.RenderPartial("ContentTypeSelector"); %></p>
<div id="CreateForm">
</div>
</asp:Content>
As you can see, it loads some HTML (actually user control) and adds it to the CreateForm div. This actually works fine.
The problem is this
$("fieldset input").each(function (index, item) {
$(item).attr("disabled", true);
});
never runs. The fieldset tag is in the response, so you don't see it here but it's there - everything is returned back fine (I checked with Firebug).
Why do the above two lines of JS never run or have any effect?
The fieldset tag doesn't exist when you call this code. Try moving this code to the inside of your success function and it might work.
function loadCreate() {
var typeId = $("#ContentTypes option:selected").val();
$.get('~/' + typeId + '/Create', function (data) {
$("#CreateForm").html(data);
$("fieldset input").each(function (index, item) {
$(item).attr("disabled", true);
});
});
}
I think your problem is here:
$.get('~/' + typeId + '/Create', function (data) {
$("#CreateForm").html(data);
});
should be:
$.get("<%=ResolveUrl("~/") %>" + typeId + "/Create", function (data) {
$("#CreateForm").html(data); // thanks Peter
$("fieldset input").attr("disabled", "disabled"); // thanks Nick
});
That's probably tossing a js exception and it's never getting to the fieldset loop.

Categories

Resources