I'm using ajaxFileUpload as described here: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AjaxFileUpload/AjaxFileUpload.aspx
It is working fine except when I have multiple file upload controls on the same page. Specifically, I am trying to upload different files for different questions. When I upload the first on the page, it works fine, but the one lower down on the page will only upload it's file into the answer for the first question.
I'm not sure that makes sense... so it may help you to know that my page is populated with questions dynamically using ascx files. The document ascx file looks like this:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Document.ascx.cs" Inherits="ScholarshipApplication.controls.questions.Document" %>
<ajaxToolkit:AjaxFileUpload OnUploadComplete="UploadComplete" ID="FileUploadControl" MaximumNumberOfFiles="1" runat="server" AllowedFileTypes="png,jpg,jpeg,pdf,tiff,tif,gif" />
<asp:LinkButton ID="downloadButton" runat="server" CausesValidation="false" OnClick="downloadButton_Click" />
And the code behind:
public void UploadComplete(object sender, AjaxFileUploadEventArgs e)
{
entry.data = e.FileName;
entry.setDocumentData(e.GetContents());
this.downloadButton.Text = e.FileName;
}
My initial thoughts are that somehow I need to help the control's generated javascript to know which question it should be triggering when.
I believe this is a bug in control or this was implemented by some non-obvious reason. Actually, this control doesn't support multiple instances on a page. Consider to use AsyncFileUpload control instead or customize a bit sources of the AjaxFileUpload control. If you prefer second option then you need to download sources from here: http://ajaxcontroltoolkit.codeplex.com/SourceControl/BrowseLatest and change AjaxFileUpload.cs file (here is a path: /Server/AjaxControlToolkit/AjaxFileUpload/AjaxFileUpload.cs). What you need to do is to change ContextKey constant to property for combining context key guid with unique id of control:
public class AjaxFileUpload : ScriptControlBase
{
private const string ContextKeySuffix = "{DA8BEDC8-B952-4d5d-8CC2-59FE922E2923}";
private string ContextKey
{
get { return this.UniqueID + "_" + ContextKeySuffix; }
}
Actually, if you'll look on PreRender method of AjaxFileUpload class you'll easy realize reson for such behavior of this control (the first control handle uploads from all sibling controls on a page).
as per my understanding You need a hidden field variable to identify your question id IN UserControl:
<input type="hidden" id="hdnQuestionId" runat="server"/>
while populating/generating question you need to set this variable , and when you upload the doc , fetch this hidden value and use it.
I created a data attribute named "data-upload-type" on ALL AjaxFileUpload controls and set it to the name of the type. Then I set up the client call to grab that value and set a cookie with the same value. The cookie IS received on the server side functions and I branch based on the value I receive.
Here is an example:
function StartUpload(sender, args) {
var t = $(sender._element).attr('data-upload-type');
document.cookie = 'upload-type=' + $(sender._element).attr('data-upload-type') + ';';
}
<asp:AjaxFileUpload ID="afuUploader1" runat="server" OnClientUploadStart="StartUpload" OnUploadComplete="UploadComplete" OnClientUploadComplete="UploadComplete" data-upload-type="UploadType2"></asp:AjaxFileUpload>
Then in your server side upload call simply check Response.Cookies("upload-type").
Works like a charm!
Related
When i need to set some value to a Javacript, or any other part of the code, i usually use this:
<script>
<%# SomeFunction() %>
</script>
And this also works for HTML in the document body, like...
<somehtmltag property="<%# SomeFunction2() %>">
And in the code behind i create the function that returns a string, with all the necessary code.
If i add some parameter to a user control like:
<ts:PeopleCard ID="us" runat="server" Visible="<%# IsVisivle() %>" />
It also works, but i try to create the entire user control it does not work.
<%# AddUserControl() %>
Function AddUserControl() as String
Return "<ts:PeopleCard ID=""us"" runat=""server"" Visible=""true"" />"
End Function
I understand that this does not work, because this code must be processed by the server to be converted in the actual code.
The final HTML, it shows:
<ts:PeopleCard ID="us" runat="server" Visible="true" />
when it shouldn't, it should show the processed HTML\css by the server.
So my question is, is it possible to create a control this way? Is it possible to force ASP.NET to "re-process" the page, after I changed its contents in code behind?
I understand there's several other ways to do it. Including, creating the user control in conde behind.
But i need to know, if is possible to do this way...
Usually you have a parent tag that is runat server and you can then add your own object to it.
Dim newTag as New PeopleCard
newTag.Visible = true
pnl.Controls.Add(newTag)
An other option I've done is the past is to add a RenderMethod to a control. Each control have a SetRenderMethodDelegate function and it allows you to write directly to the HtmlTextWriter. This won't create an object for the controls you create yourself.
I don't know how to set the value of a hiddenField in Javascript. Can somebody show me how to do this?
Javascript:
document.getElementById('hdntxtbxTaksit').value = "";
HTML:
<asp:HiddenField ID="hdntxtbxTaksit" runat="server" Value="" Visible="false"> </asp:HiddenField>
error : "Unable to get value of the property \'value\': object is null or undefined"
Prior to ASP.Net 4.0
ClientID
Get the client id generated in the page that uses Master page. As Master page is UserControl type, It will have its own Id and it treats the page as Child control and generates a different id with prefix like ctrl_.
This can be resolved by using <%= ControlName.ClientID %> in a page and can be assigned to any string or a javascript variables that can be referred later.
var myHidden=document.getElementById('<%= hdntxtbxTaksit.ClientID %>');
Asp.net server control id will be vary if you use Master page.
ASP.Net 4.0 +
ClientIDMode Property
Use this property to control how you want to generate the ID for you. For your case setting ClientIDMode="static" in page level will resolve the problem. The same thing can be applied at control level as well.
asp:HiddenField as:
<asp:HiddenField runat="server" ID="hfProduct" ClientIDMode="Static" />
js code:
$("#hfProduct").val("test")
and the code behind:
hfProduct.Value.ToString();
First you need to create the Hidden Field properly
<asp:HiddenField ID="hdntxtbxTaksit" runat="server"></asp:HiddenField>
Then you need to set value to the hidden field
If you aren't using Jquery you should use it:
document.getElementById("<%= hdntxtbxTaksit.ClientID %>").value = "test";
If you are using Jquery, this is how it should be:
$("#<%= hdntxtbxTaksit.ClientID %>").val("test");
document.getElementById('<%=hdntxtbxTaksit.ClientID%>').value
The id you set in server is the server id which is different from client id.
try this code:
$('hdntxtbxTaksit').val('test');
I suspect you need to use ClientID rather than the literal ID string in your JavaScript code, since you've marked the field as runat="server".
E.g., if your JavaScript code is in an aspx file (not a separate JavaScript file):
var val = document.getElementById('<%=hdntxtbxTaksit.ClientID%>').value;
If it's in a separate JavaScript file that isn't rendered by the ASP.Net stuff, you'll have to find it another way, such as by class.
My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response. My suggestion to solve your problem is
Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css.
If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically :
placeholderId.Attributes["style"] = "display:none";
Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.
I will suggest you to use ClientID of HiddenField. first Register its client Id in any Javascript Variable from codebehind, then use it in clientside script. as:
.cs file code:
ClientScript.RegisterStartupScript(this.GetType(), "clientids", "var hdntxtbxTaksit=" + hdntxtbxTaksit.ClientID, true);
and then use following code in JS:
document.getElementById(hdntxtbxTaksit).value= "";
Try setting Javascript value as in document.getElementByName('hdntxtbxTaksit').value = '0';
I have a web user control, it serves some potentially intensive data calculations and I would like it to be output cached so that each page view doesn't recalculate the data. It resides on very frequently viewed pages so it's quite important I get it working right!
For context, it's used on our arcade:
http://www.scirra.com/arcade/action/93/8-bits-runner
Click on stats, the data for the graphs and stats are generated from this webusercontrol.
The start of the control is as follows:
public partial class Controls_Arcade_Data_ArcadeChartData : System.Web.UI.UserControl
{
public int GameID { get; set; }
public Arcade.ChartDataType.ChartType Type { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Now the difficulty I'm having is the output cache needs to be dependant on both the GamID and the ChartType.
This control is re-used with many different combinations of GameID's and Types, I need it to create a cache for each of these but am struggling to find out how to do this.
For example, one arcade game might pass in GameID = 93 and Type = GraphData, another might be GameID = 41 and Type = TotalPlaysData and another might be GameID = 93 but Type = TotalPlaysData. These should all return different data and have different output caches.
The control is used on the games page sort of like this (the parameters are actually set in the codebehind)
<div>Total Plays:</div>
<div class="count"><Scirra:ArcadeChartData runat="server" GameID="93" Type="TotalPlays" /></div>
<br /><br />
<div>Total Guest Plays:</div>
<div class="count"><Scirra:ArcadeChartData runat="server" GameID="93" Type="TotalGuestPlays" /></div>
etc.
Any help appreciated! I've spent a while looking online and it's kept coming up as something I need to solve but can't figure this one out.
Edit
Edit: I've tried adding this line to my control:
<%# OutputCache Duration="20" VaryByControl="GameID;Type" %>
But it just throws the error Object reference not set to an instance of an object. on the line where GameID is being set for the first time on the ASPX page using the control.
When a Control is retrieved from the output cache, it's not instantiated as an instance that you can manipulate; you just get the output the Control generated, not the Control itself. For example, you can't set properties on a cached Control from code behind, as you said in your question. The vary-by properties should be set declaratively (using an ExpressionBuilder might also work, though I haven't tried it).
To see in code behind whether a control has been retrieved from the output cache, check for null:
if (this.YourControlID != null) // true if not from cache
{
// do stuff
}
Even with that caveat, Control output caching is a bit quirky.
Try this:
<%# OutputCache Duration="20" VaryByControl="GameID;Type" Shared="true" %>
The output of the Control is stored in the output cache by associating it with a certain key. With Shared="true", the cache key is the value of all specified properties, together with the Control's ID. Without Shared="true", the cache key also includes the Page type, so the output would vary by Page -- which doesn't sound like what you want.
If you use the Control on more than one page, be sure to use the same ID on each page if you can, since the ID is included as part of the key for the output cache. If you can't or don't use different IDs, you will get a new copy of the Control's output in the cache for each unique ID. If the Controls with different IDs always have different property values anyway, that may not be an issue.
As an alternative to the OutputCache directive, you can set an attribute on the class declaration:
[PartialCaching(20, null, "GameID;Type", null, true)]
public partial class Controls_Arcade_Data_ArcadeChartData : UserControl
You need to take the following steps:
1) Add the following output cache directive to the page:
<%# OutputCache Duration="21600" VaryByParam="None" VaryByCustom="FullURL" %>
2) Add the following to global.asax:
public override string GetVaryByCustomString(HttpContext context, string arg)
{
if (arg.Equals("FullURL", StringComparison.InvariantCultureIgnoreCase)
{
// Retrieves the page
Page oPage = context.Handler as Page;
int gameId;
// If the GameID is not in the page, you can use the Controls
// collection of the page to find the specific usercontrol and
// extract the GameID from that.
// Otherwise, get the GameID from the page
// You could also cast above
gameId = (MyGamePage)oPage.GameID;
// Generate a unique cache string based on the GameID
return "GameID" + gameId.ToString();
}
else
{
return string.Empty;
}
}
You can get more information on the GetVaryByCustomString method from MSDN and also review some of the other caching options here.
create a cache object in the code
HttpRuntime.Cache.Insert("ArcadeChartData" + GameID + Type, <object to cache>, null, System.Web.Caching.Cache.NoAbsoluteExpiration,new TimeSpan(0, 0, secondsToCache),CacheItemPriority.Normal, null);
above cache item will be enough to your work, but if you really want to use output cache as well try following code in the code behind,
Response.AddCacheItemDependency("ArcadeChartData" + GameID + Type);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
Setting values for the page output cache is the same as manipulating
the SetExpires and SetCacheability methods through the Cache property.
I know that my solution may look very simple and possibly weird but I tried it and it works.
You simply have to add this line in your UserControl.
<%# OutputCache Duration="10" VaryByParam="none" %>
Note : I have only tested the Framework 4.0. Also if ever you have to change the value of the property in the UserControl (MyInt, My String in this example) do it in the Page_Init event.
Here is all my code :
Page :
<%# Page Title="Home Page" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="MyWebApp._Default" %>
<%# Register Src="~/UserControl/MyUserControl.ascx" TagPrefix="uc" TagName="MyUserControl" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<uc:MyUserControl ID="uc1" MyInt="1" MyString="Test" runat="server" />
<hr />
<uc:MyUserControl ID="uc2" MyInt="3" MyString="Test" runat="server" />
<hr />
<uc:MyUserControl ID="uc3" MyInt="1" MyString="Testing" runat="server" />
</asp:Content>
User Control:
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="MyUserControl.ascx.vb" Inherits="MyWebApp.MyUserControl" %>
<%# OutputCache Duration="10" VaryByParam="none" %>
<div style="background-color:Red;">
Test<br />
<asp:Label ID="lblTime" ForeColor="White" runat="server" />
</div>
User Control Code:
Public Class MyUserControl
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Debug.Write("Page_Load of {0}", Me.ID)
Dim oStrBldr As New StringBuilder()
For i As Integer = 1 To Me.MyInt
oStrBldr.AppendFormat("{0}: {1} - {2} at {3}<br />{4}", Me.ID, i, Me.MyString, Date.Now.ToLongTimeString(), System.Environment.NewLine)
Next
Me.lblTime.Text = oStrBldr.ToString()
End Sub
Public Property MyInt As Integer
Public Property MyString As String
End Class
Please keep me posted, I have other solutions if ever you wish but they are more complex. I may also post with C#
One easy trick is to put all the graphics in a new page receiving GameId and Type as querystring parameters, use the out-of-the-box output cache for querystring parameters and the put an iframe in your page. Also you can make use of the browser's cache and never get the server hit for a while.
Ok, well the reason why this so hard to make OutputCache work in this case is because it wasn’t design to be use with Property’s, however it works very well with QueryString parameters. So my next solution isn’t the most professional and probably not the best, but it is definitely the fastest and the one that requires less code changing.
Since it works best QueryString, I recommend you putting your UserControl in one blank page, and wend ever you want to use your UserControl make an iframe that links to your page with the UserControl with QueryString.
Where you want to use your UserControl:
<iframe src="/MyArcadeChartData.aspx?GameID=93&Type=TotalPlays"></iframe>
Full page markup, MyArcadeChartData.aspx
<%# Page ... %>
<%# OutputCache Duration="20" VaryByParam="GameID;Type" %>
<Scirra:ArcadeChartData ID="MyUserControlID" runat="server />
Full page code, MyArcadeChartData.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
//TODO: Put validation here
MyUserControlID.GameID = (int)Request.QueryString["GameID"];
MyUserControlID.Type = (YourEnum)Request.QueryString["Type"];
}
Please not that values in the QueryString can be seen by the user, please do not put sensitive data.
Also I’m aware that this isn’t the most professional solution, but it is the easiest to implement, from what I know.
Regards and happy holidays
If I understand right, the caching isn't working correctly because of the way you have the properties supplying the values to the control, which probably has to do, in part, with the calculations that are being done.
You could create an HttpHandlerFactory that takes the request, does your calculations if they're not in the cache (inserting into the cache afterwards), handles the expiration of values, and then passes the request on to the page. It wouldn't be control-specific at all. That way you could use these calculated values in any control or page, and wouldn't have to implement caching policies that worry about their own calculations.
If this isn't data intensive, have you considered storing it in the Session as apposed to caching it? Just a thought...
Arcade.ChartDataType.ChartType Type;
string GameKey = GameId + Type.toString();
storedData = callCalculation(GameId,Type);
Session[GameKey] = storedData;
I realize this isn't in the cache, I am just trying to be constructive.
I have a Webpart that contains a couple of dropdowns on an update panel. There is a submit button that has the PostBackUrl set to a sharepoint Application Page
<asp:DropDownList ID="ClassSelector" runat="server" Enabled="False"
AutoPostBack="True" onselectedindexchanged="ClassSelector_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="-null-">Select Class...</asp:ListItem>
<asp:ListItem Value="1">Class 1</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnSubmit" runat="server" Text="Show Page" Enabled="False"
PostBackUrl="~/_layouts/MyWebParts/MyAppPage.aspx" />
This works in redirecting the browser to the Application Page I have created, but I am having trouble accessing the form data.
On the Page_Load function of the Application Page I have the following debugging code.
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "";
foreach (String s in Page.Request.Form.AllKeys)
{
Label1.Text += s + ": " + Page.Request.Form[s] + "<br />";
}
}
This shows that the data I need has in fact been posted to the page.
ctl00$m$g_24a73cf8_8190_4ddb_b38b_bf523b12dbd3$ctl00$SemesterSelector: 28
ctl00$m$g_24a73cf8_8190_4ddb_b38b_bf523b12dbd3$ctl00$ClassSelector: 11-0021-A
But when I try to access this as:
Page.Request.Form["ClassSelector"]
Nothing is returned. I know I must be missing something simple here, but I am not sure what.
Any help is greatly appreciated.
Ah, the ASP.NET master page prefix problem! One of my favorites.
The master page for your application page puts a prefix in front of your server-side controls so that they will be unique. If you end up access your control via the Form collection, you have to access it using not only the control ID, but also the ContentPlaceholder prefix. That's why you see such a large ID dumped out of your debugging logic.
If you want to programmatically get to the ID of the control, you can use FindControl, but you'll have to target the apppropriate content placeholder scope for this. Here's a good tutorial/explanation here (which really emphasizes how complex this can get!).
Of course, the other option you can use is just hard-coding the control id based on what you're seeing from your debugging code...but that won't be reliable if you change content placeholders or more your control to a different container.
I guess the answer depends on how static your controls will be.
Hope this helps. Good luck!!
Well to access it that way you would have to use
Page.Request.Form["ctl00$m$g_24a73cf8_8190_4ddb_b38b_bf523b12dbd3$ctl00$ClassSelector"]
As you can actually see from your code where you set the label text to s plus Request.Form[s]
i need to do the following two things...
i want to set value of in asp .net page_load. the problem is that i dont want to use runat="server". i have tried this the following but it does not work:
HtmlInputHidden hiddenControl = (HtmlInputHidden) FindControl("a");
is there a way to access in asp .net page_load without using runat="server"? ? ?
i can do this if i use but in this case i cannot access it in master page's javascript function. i have tried this but it does not work...
var hdnField = document.getElementById('<%= hdnIdentity.ClientId%>');
var hdnField = document.getElementById("hdnIdentity").getAttribute("value");
var hdnField = document.getElementById("hdnIdentity").value
what i need... i want to access content page's hidden field value in javascript in master page. is there a way ? ? ? thnx in advance regards Haroon haroon426#yahoo.com
I sometimes do the following, especially when I want control over my ids (especially when using jquery).
<asp:literal id="literal1" runat="server"><input type="hidden" id="someid" value="{0}"/></asp:literal>
Then, in codebehind you can set the value with the following:
literal1.Text = string.Format(literal1.Text, "somevalue");
This doesn't really get around using runat="server", but you haven't specified why you don't want to do that. Also, you'd have to get the value with a request.form
Update
In .net 4.0 you have much more control over your IDs. See this for more information:
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx
IIRC, you need to look in the HttpRequest.Forms, somewhere in there.
If the value is part of a POST form then you want to check Request.Forms or Request.QueryString if it's a GET form.
ad 1) in aspx file just write <input type="hidden" value="<%=GetHiddenValue%>" />. And in your code behind define protected property
public class MyPage : Page {
protected GetHiddenValue { get { /*...*/ } }
You can use it in your master page javascript how ever the control name is not what you expect it to be you'd need to use ClientID to get that. If you do not apply runat=server you can only get a hold of the control as text by either traversing the .aspx file or as some one mentioned embedding it in a named tag and then doing string manipulation on the inner HTML. That is for setting it. If you need to get the value use Request[tagName] or similar
ad 2) You can use simple html code in your content page with specified id <input type="hidden" id="myHiddenField" />. Then in master page javascript use document.getElementById('myHiddenField').