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

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>

Related

SharePoint JavaScript update choices field.set_choice does not exist

I am working with a SharePoint hosted add on that has a JavaScript component that I would like to use to update some of the choice values for one of the Site Columns I created. Everything I see indicates I should have access to a spChoiceField.Choices.Add(value), or spChoiceField.AddChoice(value), or spChoiceField.set_choices(value) but none of these are valid for me.
I am working with code that looks like:
if (clientContext != undefined && clientContext != null) {
var web = clientContext.get_web();
fieldTitle = "TQM Requesting:";
fieldChoice = clientContext.castTo(web.get_availableFields().getByTitle(fieldTitle), SP.FieldChoice);
TQMtoAdd = TQMToInsert.value;
clientContext.load(fieldChoice);
I expect fieldChoice to provide one of the add functions but it does not.
I checked the following articles:
How to update Choice column in SharePoint
Update multiple choice field in sharepoint using rest api
Sharepoint choice field
Thank you,
Duncan
Tested script in my local to update choice field of host web in SharePoint hosted add-in.
<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>
<%# Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>
<%# Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
<SharePoint:ScriptLink Name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
<meta name="WebPartPageExpansion" content="full" />
<!-- Add your CSS styles to the following file -->
<link rel="Stylesheet" type="text/css" href="../Content/App.css" />
<!-- Add your JavaScript to the following file -->
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="../Scripts/App.js"></script>
<script type="text/javascript">
var appWebContext;
var listResult;
var hostweburl;
$(document).ready(function () {
UpdateChoice();
});
function UpdateChoice() {
appWebContext = new SP.ClientContext.get_current();
hostweburl = decodeURIComponent($.getUrlVar("SPHostUrl"));
var hostwebContext = new SP.AppContextSite(appWebContext, hostweburl);
var web = hostwebContext.get_web();
var fieldTitle = "MyChoice";
var fieldChoice = appWebContext.castTo(web.get_availableFields().getByTitle(fieldTitle), SP.FieldChoice);
appWebContext.load(fieldChoice);
appWebContext.executeQueryAsync(function () {
var newValues = "NewOption";//strStatusValues.split(",");
var currentChoices = fieldChoice.get_choices();
//for (var i = 0; i < newValues.length; i++) {
// currentChoices.push(newValues[i]);
//}
currentChoices.push(newValues);
fieldChoice.set_choices(currentChoices);
fieldChoice.updateAndPushChanges();
debugger;
appWebContext.executeQueryAsync(function () {
console.log("Added new choice values to the column");
}, function (sender, args) {
deferred.reject(args.get_message());
});
},
function (sender, args) {
deferred.reject(args.get_message());
});
}
// jQuery plugin for fetching querystring parameters
jQuery.extend({
getUrlVars: function () {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function (name) {
return jQuery.getUrlVars()[name];
}
});
</script>
</asp:Content>
<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
Page Title
</asp:Content>
<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<div>
<p id="message">
<!-- The following content will be replaced with the user name when you run the app - see App.js -->
initializing...
</p>
</div>
</asp:Content>

how to pass value from javascript to ASP control

Good day,
Been new to web development (i use ASP.NET) and i had this goal of passing/returning a value to display on HTML element such such as input. I had done searching and trying most of the solutions i found but none work, the output still returns an empty value on the HTML input. why is that? my code i'm working on can be seen below:
javacript:
function confirmExistence(entityValue) {
var entity = "Staff";
var result = "";
if (entityValue === '0') {
entity = "Student";
}
if (confirm(entity + " w/ same name is already registered. is this a different " + entity + "?")) {
result = "Yes";
} else {
result = "No";
}
alert(result);
document.getElementById('<%= fieldFirstNameStudent.ClientID %>').value = result;
}
html:
<asp:button class="by-button" id="btnStudentEnc" runat="server" text="Encode" OnClick="btnStudentEnc_Click" />
<asp:textbox type="text" class="mfield" placeholder="First Name" id="fieldFirstNameStudent" runat="server" />
asp c#:
protected void btnStudentEnc_Click(object sender, EventArgs e)
{ **some sql database condition here to run the clientscript below**
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"studentConfirmExistence", "confirmExistence('0');", true); }
Result is as follows on this image:
UPDATE: IF ABOVE IS TOO COMPLICATED. i created a new web form having simple block of codes that still doesn't work
Aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="LobbyStudents.aspx.cs" Inherits="LobbyStudents" %>
<asp:Content ID="Content0" ContentPlaceHolderID="title" Runat="Server">
LobbyStudents
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script>
function confirmExistence(entityValue) {
alert(entityValue);
document.getElementById("<%= fieldFirstNameStudent %>").value = "whatswrong?";
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:textbox placeholder="First Name" id="fieldFirstNameStudent" runat="server"/>
<asp:button runat="server" text="Encode" OnClick="btnStudentEnc_Click"></asp:button>
</asp:Content>
Aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class LobbyStudents : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnStudentEnc_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"studentConfirmExistence", "confirmExistence('0');", true);
}
}
ClientScript works and even does the alert box. Still textbox is still empty and doesn't contain "whatswrong?" value
unlike i try it on this one:
<!DOCTYPE html>
<html>
<body>
Name: <input type="text" id="myText" value="tch">
<p>Click the button to change the value of the text field.</p>
<button onclick="confirmExistence('0')">Try it</button>
<script>
function confirmExistence(entityValue) {
alert(entityValue);
document.getElementById("myText").value = "whatswrong?";
}
</script>
</body>
</html>
where it works.
What's the difference between the two and why it doesn't happen on asp controls
ok, figure out what is the issue for your first example, is not related to the position, but
change your
document.getElementById("<%= fieldFirstNameStudent %>").value = "whatswrong?";
to
document.getElementById("<%= fieldFirstNameStudent.ClientID %>").value = "whatswrong?";
this will generated in html as
document.getElementById("System.Web.UI.WebControls.TextBox").value = "whatswrong?";
which the js not able to find the control name as System.Web.UI.WebControls.TextBox
if assign with .ClientID, it will generate the correct id
document.getElementById("MainContent_fieldFirstNameStudent").value = "whatswrong?";

Open a text file in new tab

I have a text file in my local drive. I want to show the content of it in a new tab.
I have tried the following
1st Try
string fileName = #"C:\MyFile.log";
Page.ClientScript.RegisterStartupScript(GetType(), "windowKey", "window.open('" + fileName + "');", true);
2nd Try
Response.Write("<script>");
Response.Write("window.open('C:\\MyFile.log', '_newtab');");
Response.Write("</script>");
Both of these open in new tab but the data inside the file is not displaying
After some search, I found this
FileStream MyFileStream = new FileStream(#"C:\MyFile.log", FileMode.Open);
long FileSize;
FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
MyFileStream.Close();
Response.ContentType = "text/plain";
Response.AddHeader("content-disposition", "inline; filename=sample.txt");
Response.BinaryWrite(Buffer);
This is displaying the content in my file but along with that it is also displaying my aspx page
So my question is how to show a text file in a new tab
try those steps
create a log.aspx and put the code from the third snippet to it.
use 1st or 2nd snippet to open log.aspx in the new window (tab)
that way it should work.
I have tried like this:
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:Button id="btnShowContent" Text="Show me the text" runat="server" OnClick="btnShowContent_Click" />
</div>
</form>
</body>
</html>
Default.aspx.cs
protected void btnShowContent_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, typeof(string), "OpenTextFile", "Javascript:window.open('Resources/test.txt');", true);
}
You just need to update your file path.
Hope this is what you want.

Uncaught error: Signalr jquery error

I am getting error while implementing Signalr in asp.net C# like:
Uncaught Error: SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.
I am implementing signalr in visual studio 2010 and I have implemented same code before but that is working fine. Please help me to resolve this error.
My code is like this:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="SignalRTest._default" %>
<!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>
<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-1.0.0-rc1.js" type="text/javascript"></script>
<script src="signalr/hubs" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
$(function () {
var IWannaChat = $.connection.myChatHub;
IWannaChat.client.addMessage = function (message) {
$('#listMessages').append('<li>' + message + '</li>');
};
$("#SendMessage").click(function () {
IWannaChat.server.send($('#txtMessage').val());
});
$.connection.hub.start();
});
</script>
<div>
<input type="text" id="txtMessage" />
<input type="button" id="SendMessage" value="broadcast" />
<ul id="listMessages">
</ul>
</div>
</form>
</body>
</html>
my code behind is like this:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports Microsoft.AspNet.SignalR.Hubs
Imports Microsoft.AspNet.SignalR
Imports System.Net
Namespace SignalRChat
<HubName("myChatHub")> _
Public Class LetsChat
Inherits Hub
Public Sub send(message As String)
message = "User : " + Dns.GetHostName() + " User :" + System.Security.Principal.WindowsIdentity.GetCurrent().Name + " Message : " + message
Clients.Caller.addMessage(message)
End Sub
End Class
End Namespace
my global.asax is like this:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application is started
RouteTable.Routes.MapHubs()
End Sub
I would write this, to set the hook on the button once connection started:
$(function () {
var IWannaChat = $.connection.myChatHub;
IWannaChat.client.addMessage = function (message) {
$('#listMessages').append('<li>' + message + '</li>');
};
$.connection.hub.start().done(function() {
$("#SendMessage").click(function () {
IWannaChat.server.send($('#txtMessage').val());
});
});
}

Assign href of anchor tag

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

Categories

Resources