define an array of input control in aspx.cs - c#

i have an input control of type file.
<input id="FileUpload1" type="file" runat="server" size="35" />
there are four input controls like this and in aspx.cs file i m trying to make an array of these ids..
i have made an array
HtmlInputFile[] fl = new HtmlInputFile[4] { FileUpload1, FileUpload2, FileUpload3, FileUpload4 };
but it gives me an error..how can i get the value of these inputs.

The
FileUploadX.PostedFile
Property is null if no file was uploaded. You need to check wether
FileUploadX.HasFile == true
before attempting to access it.
In case you are using ASP.Net AJAX updatepanels, you'll run into all sorts of proplems with FileUpload. See Link for possible solutions

Related

ASP.NET (C#) How to set/update input value of dynamically/runtime generated inputs?

I hope someone has an idea:
Short version:
In ASP.NET (C#), how can I set/update a input value of a input element, which was created on runtime (via C# or JS)?
Long version:
I use a MasterPage Site in ASP.NET and I dynamically create some input elements on the server side (C#). Now I want to access these elements, for example to change the value after Load event or after submit.
So here are some infos:
I want to code a website in C#
I need to create input elements dynamically / on runtime
After load (all elements were created) or atleast on a submit / post, I want to read SQL Data and update all input values
I don't want to use javascript / jQuery
I am not new to C#, but in ASP.NET, years ago I coded a lot in PHP (which was much easier by the way :D)
This is what I have so far, I have shortened the code a lot for better reading.
backend code of HtmlHelper.cs:
public string CreateInput(string elementId)
{
string returnHtml = "<div class='many classes'><div class='more divs'><i class='icon classes'></i><input type='text' name='" + elementId + "' id='" + elementId + "' class='some classes' runat='server' /></div></div>";
}
frontend code of users.ascx:
<form method="post" runat="server">
<%=html.CreateInput("txt_firstname") %>
<input type="submit" name="change_firstname" value="Change Input Value" runat="server" onserverclick="ChangeInputValue" />
</form>
backend code of users.ascx.cs:
public HtmlHelper html = new HtmlHelper();
protected void ChangeInputValue(object sender, EventArgs e)
{
// this will give me a readonly error
Request.Form["txt_firstname"] = "Some new value...";
// this seems to work, but the changed value is not shown in the form
var propertyInfo = collection.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
propertyInfo.SetValue(collection, false, new object[] { });
Request.Form["txt_firstname"] = "Some new value...";
}
This is what the CreateInput function returns (for example):
<div class='many classes'>
<div class='more divs'>
<i class='icon classes'></i>
<input type='text' name='txt_firstname' id='txt_firstname' class='some classes' runat="server" />
</div>
</div>
I know there are other ways to add dynamic html code, like:
<div <%=div1() %> >
<div <%=div2() %>>
<i <%=icon() %>></i>
<input id='txt_firstname' <%=input("txt_firstname") %>/>
</div>
</div>
So I can use txt_firstname.Value = "some new value..."
But I want the complete block to be dynamic and I want to use html, because I want to use the html maybe in a php project. The other problem is: On some pages there are input elements, which are created via javascript. So the user can add a "row" to save multiple values (on each "add" click I create a new input element).
It's the same problem, the input element is generated on runtime (via JS) and c# don't know this element. In PHP I can simply use the $_POST value, no matter if it's raw html or generated via PHP.
So: How can I set/update a input value of dynamically/runtime generated inputs?
Maybe my thoughts are too complicated, but there are many websites with dynamic input fields (user added rows for example), there have to be a way to update these values on the server side, or am I wrong?
And please don't hate me for generate html code as string, I try to build my own "framework", like everyone uses a framework today, and these frameworks mostly do the same, they generate code.

Why Eval does not display label and textbox?

I retrieve some html codes from database and I want to display this values in a webform.
You can see my code below. It does not display labels and textboxes. However when I View the .aspx page source in the browser I can see retrieved labels and textboxes with Eval. Why I can not see labels and textboxes in the page?
database values:
code behind:
using (BurganEntities burganEntities = new BurganEntities())
{
List<DynamicField> dynamicFields=(from dynamicField in burganEntities.DynamicField select dynamicField).ToList();
cdcatalog.DataSource = dynamicFields;
cdcatalog.DataBind();
}
aspx:
The fast answer is because asp,net controls are compiled server side but you using them as text on the final render html page - so you have skip this compile, and the asp.net page did not know nothing about them.
The solution is to avoid asp.net controls and use regular html controls. You can still get their return on code behind, you may miss some easy to use functionality, but you can make your work with alternative way.
Other possible solution is to read the database and dynamically create the controls. For example you can add a flag on your database line that says, now create a text box, and on code behind you just create that text box dynamically.
Your code is simply outputting the <asp:TextBox /> to the browser; it isn't parsing it with the WebForms processor to convert it to an <input /> element.
In your database, you should probably be storing:
<input id="txtsdsd" name="txtsdsd" class="textbox" onkeypress="return NumberOnly()" />
and then using Request.Form() to retrieve the value.
I'm not sure if you've started to write your dynamic controls but as an addition to second reply, I would like to mention more sources about dynamic controls.
Although there is no concept of controls in ASP.NET MVC any longer, you can follow ASP.NET webform data access page.
As you want to compile your code at server side; on any postback you will loose dynamic content. So read this and all done.
Or as you mentioned you didn't get values of textboxes, please see the following method,
var textBox = FindControl("<id_of_textbox>") as TextBox;
if(textBox != null)
{
var textBoxValue = ((TextBox)textBox).Text;
}
</id_of_textbox>
see FindControl method at this page

get value of hidden input field in c#

I have a charts program that works in js, but I need to update excels with the data using c#. So, what I've done so far is to create hidden input fields whose values are updated with the js variable:
<input type="hidden" name="baselineInput" id="baselineVariable" />
<input type="hidden" name="goalInput" runat="server" id="goalVariable" />
<input type="hidden" name="currentInput" runat="server" id="currentVariable" />
//do some things here
var MTDGauge = new Array(5,5,5);
document.getElementById("baselineVariable").value = MTDGauge[0];
document.getElementById("goalVariable").value = MTDGauge[1];
document.getElementById("currentVariable").value = MTDGauge[2];
The problem I'm having is reading these values back to the c# variable. Here's what I've tried (placed after the code above):
List<string> OverallData = new List<string>();
OverallData.Add(Request["baselineInput"]);
OverallData.Add(Request["goalInput"]);
OverallData.Add(Request["currentInput"]);
This is just adding null values (assuming so because the c# is loading before the javascript and the initialized values for the text fields are null?). I thought of creating a c# function that could be called using the onchange option in the input field, but that didn't get me anywhere. Is there something I'm missing? Do I have to do a post?
Thanks
Yes, to get your data back to the server (where your C# is running) you need to send it back.
POST is one way, or GET to add the values to the query string.
Javascript is only running in the browser, until you send something back to the server, your ASP.NET app will not have any information.
Of course, if you want to do it asynchronously you could use jQuery.ajax to send the data to a server URL without refreshing the whole page.

"SCRIPT5 Access is denied" error on IE9 when firing .click() from onchange

We want to reduce the number of steps it takes for a user to upload a file on our website; so we're using jQuery to open and postback files using the below markup (simplified):
<a onclick="$('#uplRegistrationImage').click();">
Change profile picture
</a>
<!-- Hidden to keep the UI clean -->
<asp:FileUpload ID="uplRegistrationImage"
runat="server"
ClientIDMode="static"
Style="display:none"
onchange="$('#btnSubmitImage').click();" />
<asp:Button runat="server"
ID="btnSubmitImage"
ClientIDMode="static"
Style="display:none"
OnClick="btnSubmitImage_OnClick"
UseSubmitBehavior="False" />
This works absolutely fine in Firefox and Chrome; opening the file dialog when the link is clicked and firing the postback when a file is selected.
However in IE9 after the file upload has loaded and a user has selected a file; insteaed of the OnChange working I get a "SCRIPT5 Access is denied" error. I've tried setting an arbitrary timeout, setting intervals to check if a file is given to no avail.
There are a number of other questions relating to this; however none appear to have a decent answer (One said set the file dialog to be transparent and hover behind a button!)
Has anyone else resolved this? Or is it absolutely necessary that I provide a button for IE users?
For security reasons, what you are trying to do is not possible. It seems to be the IE9 will not let you submit a form in this way unless it was an actual mouse click on the File Upload control that triggers it.
For arguments sake, I was able to use your code to do the submit in the change handler, but it worked only when I clicked the Browse button myself. I even set up polling in the $(document).ready method for a variable set by the change handler that indicates a submission should be triggered - this didn't work either.
The solutions to this problem appear to be:
Styling the control in such a way that it sits behind a button. You mentioned this in your question, but the answer provided by Romas here In JavaScript can I make a "click" event fire programmatically for a file input element? does in fact work (I tried in IE9, Chrome v23 and FF v15).
Using a Flash-based approach (GMail does this). I tried out the Uploadify demo and it seems to work quite nicely.
Styling a File Upload:
http://www.quirksmode.org/dom/inputfile.html
http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
References:
jQuery : simulating a click on a <input type="file" /> doesn't work in Firefox?
IE9 file input triggering using Javascript
getting access is denied error on IE8
Hey this solution works.
for download we should be using MSBLOB
$scope.getSingleInvoicePDF = function(invoiceNumberEntity) {
var fileName = invoiceNumberEntity + ".pdf";
var pdfDownload = document.createElement("a");
document.body.appendChild(pdfDownload);
AngularWebService.getFileWithSuffix("ezbillpdfget",invoiceNumberEntity,"pdf" ).then(function(returnedJSON) {
var fileBlob = new Blob([returnedJSON.data], {type: 'application/pdf'});
if (navigator.appVersion.toString().indexOf('.NET') > 0) { // for IE browser
window.navigator.msSaveBlob(fileBlob, fileName);
} else { // for other browsers
var fileURL = window.URL.createObjectURL(fileBlob);
pdfDownload.href = fileURL;
pdfDownload.download = fileName;
pdfDownload.click();
}
});
};
This solution looks like it might work. You'll have to wrap it in a <form> and get it to post in the jquery change handler, and probably handle it in form_load using the __eventtarget or and iframe or whatever it is that web forms uses, but it allows you to select a file, and by submitting the form, it should send it. I can't test it however, since I don't have an environment set up at home.
http://jsfiddle.net/axpLc/1/
<a onclick="$('#inputFile').click();">
Change profile picture
</a>
<div id='divHide'>
<input id='inputFile' type='file' />
</div>
$('#inputFile').change(function() { alert('ran'); });
#divHide { display:none; }
Well, like SLC stated you should utilize the <Form> tag.
First you should indicate the amount of files; which should be determined by your input fields. The second step will be to stack them into an array.
<input type="file" class="upload" name="fileX[]"/>
Then create a loop; by looping it will automatically be determined based on the input field it's currently on.
$("input[#type=file]:nth(" + n +")")
Then you'll notice that each file chosen; will replace the input name to the file-name. That should be a very, very basic way to submit multiple files through jQuery.
If you'd like a single item:
$("input[#type=file]").change(function(){
doIt(this, fileMax);
});
That should create a Div where the maximum file found; and attaches to the onEvent. The correlating code above would need these also:
var fileMax = 3;
<input type="file" class="upload" name="fileX[]" />
This should navigate the DOM parent tree; then create the fields respectively. That is one way; the other way is the one you see above with SLC. There are quite a few ways to do it; it's just how much of jQuery do you want manipulating it?
Hopefully that helps; sorry if I misunderstood your question.

how to get <input of type=hidden> with FindControl

I am trying to get the value of a hidden input in code behind with the following code. I am trying to cast it but it cannot find it , any help ?
((HtmlControl)FindControl("contentId"))
I declare it in aspx with the following code:
<input id="contentId" type="hidden" />
I dont want to runat server because i have my own reasons
To access a HTML control at server side (in your C# code), you need to first add the runat="server" attribute. So, your markup should look like
<input type="hidden" id="contentId" runat="server"/>
Now, in the code behind you can use the control by its id contentId itself if the code behind got generated properly.
Please let us know why you are forced to use the FindControl in the first place as it can be accessed by using the id directly.
Update
As per the comment below, the user for some reason is not interested in making this input a server side control. Then the only possibility by which you can read the values at server side is as below. But this is not advised as any changes to the name goes unnoticed and breaks at runtime.
<input type="hidden" id="contentId" name="contentName" runat="server"/>
In Code
this.Request.Forms["contentName"] would return the hidden value.
Try to search it on the page this way
HiddenField hf = (HiddenField)page.FindControl("contentId");
To get the value:
HiddenField h = (HiddenField)Gridview.FindControl("HiddenFieldName");
Then with that you can put it into a string, if you wish to.
Use this code:
string s=((HiddenField)Panel1.FindControl("contentId")).Value;
Here panel is the container control. This may be a grid or anything else or even a master page. But if you are using FindControl, i think the control may be inside some container.
HtmlInputHidden hf = Page.FindControl("contentId") as HtmlInputHidden;
string hfValue = hf.Value;

Categories