How to write value to html field from asp.net code behind - c#

I have made an application in javascript using HTML fields in asp.net, as asp text boxes were disturbing the ids, so i used html fields, which are working fine with javascript, now i want to fetch database table columns on page load, and want to assign to html fields, what is the best way to do so? Help me!!!!

You could go back to using the ASP TextBoxes and access the ids in JavaScript as follows:
<%= IDofTextBox.ClientID %>
It's probably the easiest as naturally they can then be accessed in the code behind very easily.

you can use asp text boxes fine if you grab a reference in your javascript to their asp.net generated ID via <%= textboxname.ClientId %>

This is not the right way to do it (I wouldn't recommending it), but if its what you need, then it will work.
Add method="post" action="<your path here>" to your form element and when the submit button posts, you will be able to access all the form variables like so:
string txtName = Request["TextBox1"] ?? string.Empty; //replace textbox 1 with text box name
Just be sure to replace the action in form to your page etc..
But really, going back to <asp:TextBox... will save you a lot more time and as Ian suggested, you can access them with javascript by the server tags <%= TextBox1.ClientId %>
ps: also, the ?? is a null coalesce character. its a short form of saying
if(Request["textbox1"] != null)
txtName = Request["textbox1"];
else
txtName = "";

If I understand you correctly. You just need to add runat="server" and id="someName" to the html fields and access them in the code behind by its given id.

Related

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

Dynamically change value of hidden field

For an existing site, I have to pass values in hidden fields from a form that's loaded by different pages (eg. City1.aspx, City2.aspx, City3.aspx, etc.), but they are loaded inside an iframe. I also have to dynamically change the value of at least one of those hidden field (let's call it "source") based on the city page loading it. I am familiar with PHP and JavaScript/JQuery, but I have no idea how to do this in C#.
I've found tutorials on retrieving the file name (sans extension) via JavaScript. I think I can still get the city even if the form is in an iframe, but I'd like to keep to the site's conventions and use C# if possible.
Code snippets or links to possible solutions would be much appreciated.
if you want modify the value of your input in c# associated to your aspx (Code behind), you must to add attributes runat=server to your input.
use this code in your aspx
<input id="test" type="hidden" runat="server"/>
and in your c#
test.Value = 123; //your value is 123 for example
Disclaimer, I don't know JQuery, so there could be easier ways to do this. I also haven't tested any code...
If you know the exact ID then you can do something like this from the parent page (in a javascript block):
var frame = document.getElementById('myIFrame');
var ctrl = frame.document.getElementById('myControl');
ctrl.value = "New Value";
If you don't know the exact ID's of the controls in the CityX.aspx pages, then you will either need a way for those ID's to be discovered, or you will need to go through all controls within the iframe looking for the correct one. (I say this because if the controls in the iframe pages are held in any sort of ASP.NET structure they will not be called txtMyCtrl (for instance) but possibly something like ct00_txtMyCtrl.)
If you don't know the EXACT control name (because of the ASP.NET structure I mentioned before), you could do something like:
var frame = document.getElementById('myIFrame');
var ctrls = frame.document.getElementByTagName("INPUT");
for(var i=0;i<ctrls.length;i++){
if(ctrls[i].getAttribute("type")=="hidden" && ctrls[i].id.indexOf("_myControl") != -1){
ctrls[i].value = "New Value";
break;
}
}
Or if you have the ability to update the CityX.aspx pages, then you could have the following in the CityX.aspx page:
function getCtrls(){
return [document.getElementById("<%=hiddenCtrl.ClientID%>"),
document.getElementById("<%=anotherHiddenCtrl.ClientID%>")];
}
... and then in your parent page, something like:
var frame = document.getElementById('myIFrame');
var ctrls = frame.document.getCtrls();
for(var i=0;i<ctrls.length;i++){
ctrls[i].value = "New Value";
}
They're just ideas on a general theme

How to get value of a control in a Masterpage using JQuery?

I have a hidden field control in a MasterPage and I want to get the value of the hidden field control using JQuery in a page that uses the MasterPage.
I have the following javascript which exectues if the hidden field in the page has a value:
if(!$('input[type=hidden]').val().length == 0 ) { }
What javascript would I need to check the value of a hidden field in the MasterPage from the page?
There's no seperation between your page and the master page. Both of those concepts are in your ASP.NET layer and the browser simply recieves one HTML document.
If your masterpage specified a hidden input it'll be on your page like any other hidden input.
If that has the affect you want, it should also work in the masterpage, as there is no difference on the client between a master and a content page.
The master page just gets rendered down with the child page as a single HTML, so you would just access it client-side as normal.
Try rewriting this:
if(!$('input[type=hidden]').val().length == 0 ) { }
as
if ($('input[type=hidden]').val()) {}
which is a simpler conditional for if the hidden field has a value. I'm not sure that the ! combined with the == is doing what you want it to do logically. Either way $('input[type=hidden]').val() is more readable IMO.

how do I show a string as html content in web form

I am trying to retrieve a html document to show in my web page, now the content comes from database as a string. Now I know there is a way to do this in win forms using Browser.DocumentText. But how do I do this in web form?
I tried the setting the innerHTML property for a div inside of the "OnRowCommand", the "OnRowCommand" happens to be inside an update panel. When I move the Div outside the panel, say to just below the body, it renders well.
Well there are many ways to do this, you can use a label, literal Controls.
Or maybe defining a public string within your page then use it directly in your html as:
<%= strSomeString %>
Add a literal control in aspx file and in codebehind set
Literal1.Text=data_from_DB;
Try this one:
html code:
<div id="webcontent" runat="server">
</div>
Code behind:
webcontent.InnerHtml = FromDBstring;
Write up for Mvc app Html.Raw('html tages') or MvcHtmlString.Create('html tages') and for web form HttpUtility.HtmlEncode('html tages')

ASP.NET Content page dynamic content comes out at the top of the HTML output

I'm very new to ASP.net. I have a c# content page, in which I want to inset this code half way down within the HTML:
<%
HttpResponse r = Response;
r.Write(HttpContext.Current.Request.ServerVariables["SERVER_NAME"]);
%>
But when I view the page, this content comes out first, before even the tag.
Any ideas on how to get this code inline instead?
Thanks!
EDIT
I'd just like to add a note to all who answered this question to explain what you've done.
You spared your valuable time to help me, a stranger to you, solve a difficult problem at work, which allowed me to get out of the office on Friday night, just in time to catch the last bus to my home 50 miles away, and see my wife who was sick in bed. You didn't just answer my question, you made my day SO much better. THANK YOU so much!
Steven
Because you are doing a Response Write, that will push out before everything else. If you want to just imbed something at a specific point you can do:
<%= HttpContext.Current.Request.ServerVariables["SERVER_NAME"]) %>
This <%= %> will write any string to that exact location in the HTML.
You could also use a Literal control and assign its Text property in your codebehind or use a Label if you require formatting.
You can put a label on the page where you want the text to appear and then set the label's text instead of doing like this. Simply put an asp label on the page and frmo your code behind do
myLabel.Text = HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString();
where myLabel is the ID of your label in your HTML Markup.
Define a DIV on the page like this, where you want the outputted string to be displayed:
<div id="myDIV" runat="server" />
Then, instead of r.Write() you can simply set the inner text of the DIV to be what you want:
myDIV.innerText = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
when you use Response.Write("..."); its shows up before page header , instead of using Response.Write you can put a label on the form wherever you want to see the message and set label's Text property.
Or if you just want the text, with no html markup.
Use a literal.
In aspx file
<asp:Literal ID="MyLiteral" runat="server" />
in code-behind
MyLiteral.Text = HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString();

Categories