How to get input element from Literal - c#

On the sever side, I've created, a literal with text set to an input type file element with runat = 'server' property, mode set to passThrough and append it to a div. Both the literal and input element have it's own unique id. My issue is trying to get that input element from the div tag. I'm able to get the literal programmatically, but the literal doesn't contain any controls and text value has the input element I need. I tried looking for the input element o it's own and keep getting null. I've inspected the page and I see the input element with runat='server'and it's and yet I can't get it. I need to be able to get this input element in order to upload it's file.
This is what I've tried so far:
Client-Side:
<div runat="server" id="docRequeridosMainDiv" style="display: table;
width: 60%; text-align: right">
<%-- Control set on server side --%>
</div>
Server-Side: (Testing this on pageload event)
//Attach inivisible input type file
uploadLit.Text += string.Format(#"<div><input type='file' id='{0}File' runat = 'server' style='display: none;'
onchange='" + docsRequeridos.ElementAt(i).Nombre + #"FileSelected()' /></div>", lbl.Text);
uploadLit.ID = lbl.Text + "FileLit";
docRequeridosMainDiv.Controls.Add(uploadLit);
//var lit = (Literal)docRequeridosMainDiv.FindControl(uploadLit.ID);
var lit = (HtmlGenericControl)docRequeridosMainDiv.FindControl(lbl.Text +"File");
Ignore the event attached to input, that works.
I've debugged the commented lit and on the controls collection has 0 but the text has the input. The second lit is returns a null value.
Tried getting it with the same Findcontrol line on a click event and still same result. Literal with no controls.
Just in case you're wondering why the input is display:none cause I'm doing a custom file upload, but that's not important cause every other functionality works, the only on that doesn't work is this one.

FindControl() will find only server controls. Adding html control (with runat="server" as string) into a Literal will not make those controls servier-side. But you can use HtmlInputFile to achieve the same, like this:
var fileInput = new HtmlFileInput
{
ID = lbl.Text + "File"
};
fileInput.Attributes["onchange"] = docsRequeridos.ElementAt(i).Nombre + "FileSelected()";
fileInput.Attributes["style"] = "display:none";
docRequeridosMainDiv.Controls.Add(fileInput);
Now, you can find this control like:
var foundFileInput = docRequeridosMainDiv.FindControl(lbl.Text +"File") as HtmlFileInput;
If you want to wrap this file input with div, you need to make another HtmlGenericControl and add that fileInput to that; like this:
var myDiv = new HtmlGenericControl("div")
{
ID = "FileUploadContainer"
};
myDiv.Controls.Add(fileInput);
docRequeridosMainDiv.Controls.Add(myDiv); // Add myDiv instead of fileInput
This will generate exactly the html you wanted, but just programmatically (not with Literal string), and controls are now server-side.

Related

Get clientID for multi userControl with same Server ID

I have ASP.Net application that have multiple User Controls in the same page every one have its hidden field that holds a value, and every one have button that calls pop-up and through this value from hidden field to it.
The problem that when i try to access the hidden field and get the value inside , the program always get the last one (which created last).
How can i get the value of the inner hidden field in the current UserControl (Which i'm clicking the button from)?
Attempts:
var hdnRegion = "<%=hdnRegionId.ClientID%>";
var regionIdVal = $("#" + hdnRegion).val();
methodName(regionIdVal);
another one:
var currentControl = "<%=this.ClientID%>";
var hdnRegion = currentControl + "_" + "hdnRegionId";
var regionIdVal = $("#" + hdnRegion).val();
methodName(regionIdVal);
I also tried to call a property from code behind that returns the value and one that returns the whole control with no correct result.
Any suggestions would be appreciated...
Accourding to your comment under the question, your btnUpdate and hdnRegionId controls are in the same container (for instance in the same div) so try this:
$('input[id*="btnUpdate"]').click(function(){
var regionIdVal = $(this).parent().children('input[id*="hdnRegionId"]').val();
methodName(regionIdVal);
});
This is a JSFiddle Demo that simulate your HTML code that is rendered by ASP.NET.

Ghost cell in IE9 with Repeater Control

IE9 Generate blank cell or you can say Ghost Cell, with ASP.Net Repeater control.
I try javascript regural expression. Render function to run reg. exp. but the page holds few update controls and generate error.
Error: sys.webforms.pagerequestmanagerservererrorexception the message
received from the server could not be parsed. ScriptResource.axd
I try all the well known links for this error.
Please suggest me if you really have...
Thank You
protected override void Render(HtmlTextWriter writer)
{
using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
{
base.Render(htmlwriter);
string html = htmlwriter.InnerWriter.ToString();
if ((ConfigurationManager.AppSettings.Get("RemoveWhitespace") + string.Empty).Equals("true", StringComparison.OrdinalIgnoreCase))
{
//html = Regex.Replace(html, #"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[\n])\s{2,}", string.Empty);
html = Regex.Replace(html, #"(?<=<td[^>]*>)(?>\s+)(?!<table)|(?<!</table>\s*)\s+(?=</td>)", string.Empty);
html = html.Replace(";\n", ";");
}
writer.Write(html.Trim());
}
another Solution is, but fail for Repeater
var expr = new RegExp('>[ \t\r\n\v\f]*<', 'g');
document.body.innerHTML = document.body.innerHTML.replace(expr, '><');
You can access the Repeater control directly (before it's written to the page and rendered by IE) and remove the cells based on their index.
Need to remove spaces between "< /td >" and "< td >".
Found a very useful script to prevent unwanted cells in your html table while rendering in IE9 browser.
function removeWhiteSpaces()
{
$('#myTable').html(function(i, el) {
return el.replace(/>\s*</g, '><');
});
}
This javascript function you should call when the page loads (i.e. onload event)

How can I use a JavaScript variable to get an ASP.NET ClientID inside a JavaScript function?

I'd like to be able to get a ASP.NET control's ClientID inside of a JavaScript function. I also would like to be able to pass in a var containing a control name so that different controls can use the same function.
For example, if I wanted to use a control named Button1, this works fine:
function doStuffToButton1Control()
{
var buttonControl = document.getElementById('<%= Button1.ClientID %>');
//do stuff with buttonControl
}
But I get an error when I try to make the control name dynamic. I'm trying to string together the ClientID call, like so:
function doStuffToGenericControl(controlName)
{
var dynamicControl = document.getElementById('<%= ' + controlName + '.ClientID %>');
//do stuff with dynamicContorl
}
I've tried using double quotes or single quotes when creating the string, but the error is always "Too many characters in string literal" or "Too many characters in character literal". The control exists and the name passes correctly (as tested by an alert(name)).
Is there a better way to go about this, or am I missing something obvious?
Thanks!
Update: This function will be on a master page. Any number of child pages will be calling it. For example, one child page might have an ASP control that calls it like so:
<asp:LinkButton ID="Button2" runat="server" OnClientClick="doStuffToGenericControl('Button2')">...</asp:LinkButton>
But another page might have this ASP control that also calls it:
<asp:LinkButton ID="Button4" runat="server" OnClientClick="doStuffToGenericControl('Button4')">...</asp:LinkButton>
However, these controls' IDs often change by ASP.NET on render, so they end up looking, for example, like MainContent_Button2 instead of just Button2. To get around this, I traditionally just used <%= Button1.ClientID %>, but since I want any number of controls to be able to use this one function, I'm having a bit of trouble.
Update 2: I was able to use this along with a getAttribute call to get what I needed. (Obviously this will only work when the control you are referring to is the one you are clicking, but that is what I needed) Like so:
function doStuffToGenericControl(controlName)
{
var controlID = controlName.getAttribute('id');
var control = document.getElementById(controlID);
//do stuff with control
}
'<%= Button1.ClientID %>' is something that replaced in with control id on asp.net page render,
but when you pass variable in client side, you should pass id and use it without any % scops
so try this
function getGenericControl(control)
{
var dynamicControl = control;
alert(dynamicControl);
//do stuff with dynamicContorl
}
UPDATE
You can use <%= ClientID %> to generate parameters for the method above, so just change OnClientClicks like this and use method above
<asp:LinkButton ID="Button2" runat="server" OnClientClick="doStuffToGenericControl(this)">...</asp:LinkButton>
Rather than passing control name why don't you pass the control itself by passing this in the function like this:
<asp:LinkButton ID="Button2" runat="server" OnClientClick="doStuffToGenericControl(this)">...</asp:LinkButton>
and your function will be :
function getGenericControl(control)
{
var dynamicControl = control;
alert(dynamicControl.id);
//do stuff whatever you want with dynamicContorl
}
I would strongly suggest using a class if that is possible,
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
> -1) {
elems[i].innerHTML = content;
}
}

get height of div from masterpage

How can I get the height of a div which is placed inside a masterpage?
I'm able to set the height as follow:
((HtmlControl)this.Master.FindControl("sidebar")).Style.Add("height", "600px");
Now I'm trying to get the height from my div called mainPage, how can I do this?
MasterPage.Master:
<div id="_test" style="height: 100px" runat="server"></div>
MasterPage.Master.cs:
public HtmlGenericControl test
{
get { return this._test; }
}
any other cs-file:
string width = ((MasterPage)this.Master).test.style["height"];
Edit: If you want to get any style information created dynamically you will need to store this information into a hidden field, because you won't be able to retrieve the data by calling style["x"] in the postback.
Edit2: Adjusted masterpage-name.
You will have to get the div's height on the client side as it may be rendered differently for each client...
Using jQuery, you can do
$("#sidebar").height();
but for this you will have to wait that the document is ready. So you can put this line in the ready function of the document:
$(document).ready(function(){});
EDIT
Another solution is adding runat="server" to your div
<div ID="sidebar" runat="server">...</div>
Then from your code you can do something like
HtmlGenericControl sb = this.form1.FindControl("sidebar") as HtmlGenericControl;
int sidebarHeight = sb.Height;

How to find the Controls in panel (which is added through literal)

Textbox1.text is user can enter html page name, so that its is appending to panel through literal.(loading html page to pannel).
string val = TextBox1.Text;
string location = Server.MapPath(".");
string path = location + "\\HTML\\" + val + ".html"; // HTML IS FOLDER NAME IN MY PROJECT
string readText = System.IO.File.ReadAllText(path);
Panel1.Controls.Clear();
Literal lit = new Literal();
lit.Text = readText;
Panel1.Controls.Add(lit);
Actually in Html page few controls which are in format of input (<input style="position: relative;" id="T0" onmouseup="mUp(this.id)" class="ui-draggable" onmousedown="mDown(this.id)" value="" type="text">)
I have to find those id's and text to save in database.
how to find the controls in panel now?
Give an ID to the control when you add it.
Literal lit = new Literal();
lit.Text = readText;
lit.ID = "myLiteral";
Panel1.Controls.Add(lit);
Then you can get it back as follows:
Literal lit = (Literal)Panel1.FincControl("myLiteral");
Remember that dynamically added controls must be created added again on every PostBack that follows as long as you want to have access to them.
Give your Literal an ID and then you can access it via FindControl...
Literal myLiteral = Panel1.FindControl("litId") as Literal;
if (myLiteral != null)
{
// ... do something
}
EDIT: (Missed the last part of your question)
You need to use ParseControl([string value]) on the HTML content which returns a control and then add that control (containing all child controls) to the Panel. Then you can use FindControl to locate child controls. For this method, the controls must be .NET controls (ie.
Since you did not give id to the control, u can find them by Panel1.Controls[index], since it is the first control added u can access at Panel1.Controls[0]

Categories

Resources