SharePoint JavaScript update choices field.set_choice does not exist - javascript

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>

Related

Sharepoint 2013 Hosted App execute javascript on all pages load

I would like to know if it's possible to have a SP 2013 Hosted app that injects a piece of Javascript that gets executed on every page load.
For the sake of simplicity, imagine that I want to create an App that on every page load of the SP Site displays a alert('Hello world!');
I don't want to have a Remote Web, pure and simple Hosted App that can be added by anyone simply by picking it from the SP Store.
Is this possible?
Thanks!
You can inject the javascript using a custom action script link as #AlexCode suggests but the app will require web - full control permissions. I can't remember where I adapted this code from while I was looking into add-in development. Also this is for POC only you should probably look to make it more robust before using it in a live environment.
App.js contents
(function(undefined) {
"use strict";
var actions, web, context, hostContext, actionDescription;
console.log('running function');
// getQueryStringParameter: method to retrieve query string parameter values
var getQueryStringParameter = function(param) {
var params = document.URL.split('?')[1].split('&');
var length = params.length;
for (var i = 0; i < length; i = i + 1) {
var singleParam = params[i].split('=');
if (singleParam[0] == param) {
return singleParam[1];
}
}
};
// inject: method to return as a string the js that will be ran by the custom action
var inject = function() {
debugger;
var scriptToRun;
scriptToRun += '(function (){' +
'var elem = document.getElementsByTagName("head")[0];' +
'var script = document.createElement("script");' +
'script.appendChild(document.createTextNode(alert("hello world")));' +
'elem.appendChild(script);' +
'}());';
return scriptToRun;
};
var success = function() {
alert('Done');
}
var fail = function() {
alert('Failed');
}
// unprovision: removes the custom action and the JavaScript file
var unprovision = function() {
context = SP.ClientContext.get_current();
hostContext = new SP.AppContextSite(context, decodeURIComponent(getQueryStringParameter('SPHostUrl')));
// load the custom actions from the host web
actions = hostContext.get_web().get_userCustomActions();
context.load(actions);
web = hostContext.get_web();
context.load(web);
context.executeQueryAsync(unprovisionEx, fail);
};
// unprovisionEx: method to remove the custom action
var unprovisionEx = function() {
var enumerator = actions.getEnumerator();
var removeThese = [];
// find the custom action
while (enumerator.moveNext()) {
var action = enumerator.get_current();
if (action.get_description() == actionDescription && action.get_location() == 'ScriptLink') {
// add it to a temporary array (we cannot modify an enumerator while enumerating)
removeThese.push(action);
}
}
// do the actual removal of the custom action
var length = removeThese.length;
for (var i = 0; i < length; i++) {
removeThese[i].deleteObject();
delete removeThese[i];
}
context.executeQueryAsync(success, fail);
};
// provisionScriptLink: method that adds the custom action
var provisionScriptLink = function() {
var enumerator = actions.getEnumerator();
var removeThese = [];
// check if the custom action already exists, if it does then remove it before adding the new one
while (enumerator.moveNext()) {
var action = enumerator.get_current();
if (action.get_description() == actionDescription && action.get_location() == 'ScriptLink') {
removeThese.push(action);
}
}
var length = removeThese.length;
for (var i = 0; i < length; i++) {
removeThese[i].deleteObject();
delete removeThese[i];
}
// create the custom action
var newAction = actions.add();
// the 'description' is what we'll use to uniquely identify our custom action
newAction.set_description(actionDescription);
newAction.set_location('ScriptLink');
newAction.set_scriptBlock(inject());
newAction.update();
context.executeQueryAsync(success, fail);
};
// provision: starts with uploading the JavaScript file to the host we, once done it will continue with the provisionScriptLink() method
var provision = function() {
context = SP.ClientContext.get_current();
hostContext = new SP.AppContextSite(context, decodeURIComponent(getQueryStringParameter('SPHostUrl')));
// load the custom actions from the host web
actions = hostContext.get_web().get_userCustomActions();
context.load(actions);
web = hostContext.get_web();
context.load(web);
context.executeQueryAsync(provisionScriptLink, fail);
};
document.getElementById("add").onclick = provision;
}());
Default.apsx content
<%-- 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="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# 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" %>
<%-- 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="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<!-- Add your CSS styles to the following file -->
<link rel="Stylesheet" type="text/css" href="../Content/App.css" />
</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>
<button type="button" value="add" name="add" id="add">Add</button>
</div>
</asp:Content>
<asp:Content ContentPlaceHolderID="PlaceHolderUtilityContent" runat="server">
<!-- Add your JavaScript to the following file -->
<script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>
You can provide a custom master page to the host site from app site via javascript. Anyway the host site must use the new master page.
You can see this article for more info

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

jQuery append() under an element ID?

I am building a navigation bar that is driven based off of values retrieved from a SharePoint List. Right now, I am using an <ul> for my column headers and <li> for my contents. I can get the headers to display correctly and can also get the contents of that column to display correctly. What I'm having troubles with is that the <li> seems be appended to the <ul> which is great, but it's also putting it inside of it. My <ul> has a border around it and I want the content to be appended directly under that border but instead, it's putting everything inside of it.
Here is the specific block of code I believe is wrong:
$('#TableElement').hover(function () {
$('[id^=Header]').hover(function () {
$("#" + this.id).append("<li>" + this.id + "</li>");
});
});
Here is all of my code:
/////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////
////////////////////////////////////////EVERYTHING BELOW THIS LINE IS GOOD TO GO/////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////
//Print Headers to Screen. This will drive the core functionalty of the navpart
var siteUrl = '/sites/dev';
ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
theCounter = 0;
var Headers = new Array();
var getCurrentElementId = null;
function retrieveListItems() {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('myList');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<Where><IsNotNull><FieldRef Name='Title' /></IsNotNull></Where>");
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args) {
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
theCounter += 1;
Headers[theCounter - 1] = oListItem.get_item('Title');
}
var HeaderDisplay = _.uniq(Headers);
for (var i = 0; i <= HeaderDisplay.length - 1; i++) {
$('#TableElement').append("<th id=Header" + i + ">" + HeaderDisplay[i] + "::::::" + "</th>");
}
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
/////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////
////////////////////////////////////////EVERYTHING ABOVE THIS LINE IS GOOD TO GO/////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////
// You got the headers to print as expected. Right now you need to figure out how to get the current ID
// that the mouse is over. Try looking at another project you did where the mouse goes into the table header
// and the outline expands.
$('#TableElement').hover(function () {
$('[id^=Header]').hover(function () {
// Come back to this::::::: var content = $(this).html();
$("#" + this.id).append("<li>" + this.id + "</li>");
});
});
//This should be the universal onmouseover event that will expose only links
//and values relavent to the selected header.
//$(document).ready(function onPageLoad() {
// $().SPServices({
// operation: "GetListItems",
// async: false,
// listName: "myList",
// CAMLQuery: "<Query><Where><IsNotNull><FieldRef Name='Title' /></IsNotNull></Where></Query>",
// completefunc: function completeFunction(xData, Status) {
// $(xData.responseXML).SPFilterNode("z:row").each(function () {
// var Headers = "<th>" + $(this).attr("ows_Title") + "</th>";
// $("#TableElement").append(Headers);
// });
// }
// });
//});
HTML Code:
<%# Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%# Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%# Import Namespace="Microsoft.SharePoint" %>
<%# Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1UserControl.ascx.cs" Inherits="AnotherMarcPart.VisualWebPart1.VisualWebPart1UserControl" %>
<!DOCTYPE Html />
<html>
<head>
<link rel="Stylesheet" type="text/css" href="c:\users\administrator\documents\visual studio 2010\Projects\AnotherMarcPart\AnotherMarcPart\VisualWebPart1\Stylesheet1.css" />
<title></title>
</head>
<body>
<ul id="TableElement"></ul>
<script type="text/javascript" src="c:\users\administrator\documents\visual studio 2010\Projects\AnotherMarcPart\AnotherMarcPart\VisualWebPart1\jQuery_v1.10.2.js"></script>
<script type="text/javascript" src="c:\users\administrator\documents\visual studio 2010\Projects\AnotherMarcPart\AnotherMarcPart\VisualWebPart1\jquery.SPServices-2013.01.js"></script>
<script type="text/javascript" src="c:\users\administrator\documents\visual studio 2010\Projects\AnotherMarcPart\AnotherMarcPart\VisualWebPart1\Underscore.js 1.5.2.js"> </script>
<script type="text/javascript" src="c:\users\administrator\documents\visual studio 2010\Projects\AnotherMarcPart\AnotherMarcPart\VisualWebPart1\JScript1.js"></script>
</body>
</html>
<li> tags must go inside a <ul>. If you want your content after the <ul>, then don't put it in an <li> (perhaps put it in a <div> instead) and use jQuery's .after() or .insertAfter() to put it after the <ul>.
Also, this code is likely wrong:
$('#TableElement').hover(function () {
$('[id^=Header]').hover(function () {
$("#" + this.id).append("<li>" + this.id + "</li>");
});
});
You don't want two .hover() handlers inside of one another. You will be installing the second .hover() over and over every time you hover over the first one. That will give you lots of duplicate event handlers and the function inside will get executed multiple times.
If .insertAfter() isn't exactly what you want, then show us your HTML and show us exactly where you want the new content inserted. You said you wanted it after the <ul> tag's border so that's what .insertAfter() will do.
Based on how you've edited your question, you would append to that other UL like this:
$("#TableElement").append("<li>" + this.id + "</li>");
That will make the <li> be the last <li> inside of the TableElement <ul> which will be inside it's border. There is no way to put an <li> inside a <ul> and have the <li> be outside the border around the <ul>. To do that, you would have to create a container object AFTER the <ul> and put the content into that container instead.

how to display data in List Or grid or in table in Jsp

This is my JSP code:
<%#page import="java.util.Calendar"%> <%# page import="org.apache.lucene.search.IndexSearcher"%> <%# page import="org.apache.lucene.analysis.Analyzer"%> <%# page import="org.apache.lucene.analysis.snowball.SnowballAnalyzer"%> <%# page import="org.apache.lucene.search.Hits"%> <%# page import="org.apache.lucene.queryParser.QueryParser"%> <%# page import="org.apache.lucene.queryParser.MultiFieldQueryParser"%> <%# page import="org.apache.lucene.queryParser.ParseException"%>
<%# page import="org.apache.lucene.queryParser.QueryParser"%> <%# page import="org.apache.lucene.search.Query"%>
<%# page import="org.apache.lucene.util.Version"%> <%# page import="org.apache.lucene.store.FSDirectory"%> <%# page import="org.apache.lucene.search.ScoreDoc"%> <%# page import="org.apache.lucene.document.Document"%> <%# page import="org.apache.lucene.search.ScoreDoc"%>
<%# page import="org.apache.lucene.index.IndexReader"%>
<%# page import="java.io.IOException"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import="java.io., java.net."%>
<% //out.print("Today is:"+Calendar.getInstance().getTimeInMillis());
String fil = "E:\\cbdtindex";
Analyzer analyzer = new SnowballAnalyzer("English");
IndexSearcher indexSearcher;
String[] fields = { "DocType1" };
try {
// Directory indexDir = FSDirectory.open(findexfile);
IndexReader reader = IndexReader.open(
FSDirectory.open(new File(fil)), true);
indexSearcher = new IndexSearcher(reader);
MultiFieldQueryParser parser = new MultiFieldQueryParser(
fields, analyzer);
Query query = parser.parse("dtl");
ScoreDoc[] hits = indexSearcher.search(query, null, 100000).scoreDocs;
int x = hits.length;
for (int i = 0; i < x; i++) {
Document hitDoc = indexSearcher.doc(hits[i].doc);
String p = hitDoc.get("FilePath");
//System.out.println(p);
out.println(p);
}
System.out.println("Length" + x);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
%>
I want to display String P Value in List Gird or Table.
Can someone help me? I am able to print display data in out.print.ln on console, but I need to display in List.
You can use jstl <c:forEach> for iteration and html <table><tr><td></td></tr></table> for text formatting. And it's better to use jsp as a view only without scriptlets.

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>

Categories

Resources