Loading content around TextBoxes in ASP.NET - c#

I'm trying to create a form in ASP.NET but I'd like to know if I can dynamically add HTML content around a TextBox.
Here is the code:
<%# Page Title="" Language="C#" MasterPageFile="~/MPpacientes.master" AutoEventWireup="true" CodeFile="CuestionarioGeneral.aspx.cs" Inherits="CuestionarioGeneral" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="navbar" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="headertitle" Runat="Server">
Cuestionario General
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="contentbox" Runat="Server">
<legend>Lorem ipsum dolor sia met etcetcetc</legend>
<%-- question1 --%>
<asp:Label ID="lbl1" runat="server" Text="1"></asp:Label>
<div class="input-control text" data-role="input-control">
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
<button class="btn-clear" tabindex="-1"></button>
</div>
<%-- question2 --%>
<asp:Label ID="lbl2" runat="server" Text="2"></asp:Label>
<div class="input-control text" data-role="input-control">
<asp:TextBox ID="txt2" runat="server"></asp:TextBox>
<button class="btn-clear" tabindex="-1"></button>
</div>
<%-- question3 --%>
<%-- etc --%>
As you can see in the code, the content of the < div > and the < button > tags don't change at all in each question, so I wanna know if there's some way to load them from a script so that when the page loads they wrap around each TextBox automatically.
Thanks in advance.

did the total question for each page different or the same?
if different, you can try to use asp:Repeater for that. You can dynamically change the question, and keep the button and div static for every question.
for example :
<asp:Repeater ID="rptQuestion" runat="server" OnItemDataBound="rptQuestion_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lblQuestion"></asp:Label>
<div class="input-control text" data-role="input-control">
<asp:TextBox ID="txtAnswer" runat="server"></asp:TextBox>
<asp:Button CssClass="btn-clear" TabIndex="-1" ID="btnClear" runat="server"></button>
</div>
</ItemTemplate>
</asp:Repeater>
Edit :
to edit the Label text, you can first add all your question to List<String> then Bind it to the repeater, here's the example :
on PageLoad :
protected void Page_Load(object sender, EventArgs e)
{
List<String> listQuestion = new List<String>();
foreach(string question in ...)
{
listQuestion.Add(question);
}
rptQuestion.DataSource = listQuestion;
rptQuestion.DataBind();
}
then on the ItemDataBound event :
protected void rptQuestion_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
String question = (String)e.Item.DataItem;
Label lblQuestion = (Label)e.Item.FindControl("lblQuestion");
lblQuestion.Text = question;
}
}
you don't need to change the ID for the Label and TextBox, because it will always be different for each item in the repeater

If you just need to add a question, you can a <asp:label /> tag, or even a Html label tag and make it runat="server".
And then you can add the text to the label dynamically in the code behind

Related

Select2 is being duplicated in my component

I am using the jquery plugin in my pages e until now i have not any problem with it. the problem happend when i am tring using the select2 with a ascx page. More description of the problem below.
I have a aspx that i am using a component ascx to show somethings:
<%# Page Title="" Language="C#"
MaintainScrollPositionOnPostback="True" AutoEventWireup="true"
CodeBehind="Register.aspx.cs" Inherits="Organization.Register" %>
<%# Register Src="../DialogUF.ascx" TagPrefix="comp" TagName="DialogUF" %>
<asp:Content runat="server">
<asp:LinkButton ID="btnUF" runat="server" CausesValidation="False"
OnClick="btnUF_Click">aqui</asp:LinkButton>
<Comp:DialogUF ID="dlgUF" runat="server" />
</asp:Content>
In My code behind:
protected void btnUF_Click(object sender, EventArgs e)
{
dlgUF.Visible = true;
}
Mas ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="DialogUF.ascx.cs"
Inherits="Organization.DialogUF" %>
...
<asp:Panel ID="pnlBody" runat="server">
<fieldset class="grid-form">
<div data-row-span="12">
<div data-field-span="6">
<asp:Label runat="server" AssociatedControlID="ddlState">UF
<span class="text-danger">(*)</span>:</asp:Label>
<asp:DropDownList ID="ddlState" runat="server"
CssClass="form-control"
OnSelectedIndexChanged="ddState_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
</div>
</div>
</fieldset>
...
<script type="text/javascript">
$(document).ready(function () {
$("#<%= ddlState.ClientID %>").select2();
});
</script>
</asp:Panel>
Image of select2 duplicated

textBox.text is empty in onClick function Server side

I have a very simple asp.net page and something not working as it should be.
This is the structure of my page:
<%# Page Title="" Language="C#" MasterPageFile="~/Management/page.master" AutoEventWireup="true" CodeFile="Account.aspx.cs" Inherits="_Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<div class="contentWrapper">
<asp:Panel runat="server" ID="MainPanel" ClientIDMode="Static" CssClass="MainPanel" OnLoad="MainPanel_Load">
..........
..........
..........
..........
..........
..........
<asp:Panel runat="server" id="PasswordHolder" CssClass="rtl" Width="100%" ClientIDMode="Static">
<asp:TextBox runat="server" ID="PasswordInput" CssClass="block" TextMode="Password" />
<asp:LinkButton runat="server" CssClass="btn ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" ID="EditBtn" OnClick="EditBtn_Click"><span class="ui-button-text">submit</span></asp:LinkButton>
</asp:Panel>
</asp:Panel>
</asp:Content>
Now: I'm entering a text in the TextBox(PasswordInput) and clicking submit.
The Server catch the event and entering EditBtn_Click function.
BUT! PasswordInput.Text is empty.
What should I do to fix that?
Server Side Code:
protected void Page_Load(object sender, EventArgs e)
{
if (currentUser() == null)
{
Response.Redirect("Login.aspx", true);
}
if (!IsPostBack)
{
ViewState["ContactsSortExpression"] = "LastName";
ViewState["ContactsSortDirection"] = "ASC";
}
}
protected void EditBtn_Click(object sender, EventArgs e)
{
if (PasswordInput.Text == currentUser().Password)
{
//Do something
}
}
My Problem was the Jquery dialog function
For an answer look here:
asp.net Textbox value is null when post bock with Jquery Dialog occured

ClientSideEvents on ASP:Net repeater control

I'm creating a textbox control in a repeater. Here is .cs code:
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Est estimationItem = (Est)e.Item.DataItem;
TextBox txtWeekly = (TextBox)e.Item.FindControl("txtWeekly");
txtWeekly.Text = estimationItem.SMEst.ToString();
}
And here is .aspx code:
<asp:Repeater ID="WeeklyEst" OnItemDataBound="WeeklyEst_ItemDataBound" runat="server">
<HeaderTemplate>
<table>
<tr>
</HeaderTemplate>
<ItemTemplate>
<td>
<asp:TextBox ID="txtWeekly" runat="server">
<ClientSideEvents OnTextChanged="function(s, e) { alert('AlertIsHere!');}" />
</asp:TextBox>
</td>
</ItemTemplate>
<FooterTemplate>
<td>
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
I want to do is firing an alert when text changed on text box. How can I do this? CliendSideEvent fire on another textbox but in repeater control, it doesn't work.
Use the ItemDataBound event of Repeater control, you can do this like..., if i understood you correctly
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item)
{
TextBox mytxt = e.Item.FindControl("txtWeekly") as TextBox;
// you can just pass "this" instead of "mytxt.ClientID" and get the ID from the DOM element
mytxt.Attributes.Add("onchange", "doStuff('" + mytxt.ClientID + "');");
}
}
if you donot want to do this in codebehind then you can use jquery ,it would be lot easier
$('.txtbox').change(function() {
alert($(this).val());
});
just give cssclass 'txtbox' to your textbox.
What about this unobtrusive approach
<head runat="server">
<title></title>
<script type="text/javascript" src="js/jquery-1.7.1.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
// select all input text ending with txtWeekly as repeater control
// will create something like rptWeeklyEst$ctl00$txtWeekly
$('input[name$="txtWeekly"][type=text]').change(function () {
alert('textbox changed to ' + $(this).val());
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="rptWeeklyEst" runat="server">
<ItemTemplate>
<asp:TextBox ID="txtWeekly" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:Repeater>
<br />
Nope
<asp:TextBox ID="txtNope" runat="server"></asp:TextBox>
</div>
</form>
</body>

Pass value back to server in asp.net?

In an asp.net application, I have the follow code in the aspx page:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% foreach (var questionPaper in QuestionPapers) { %>
<div style="border-bottom: 1px solid; padding-bottom:20px">
<%= questionPaper.University %><br/>
<%= questionPaper.CourseName %>: <%= questionPaper.CourseCode %><br/>
<%= questionPaper.Type %><br/>
<%= questionPaper.Year %><br/>
<asp:Button ID="View_Paper" runat="server" OnClick="ViewPaper" Text="View Paper"/>
</div>
<% } %>
</asp:Content>
I want to pass questionPaper.ID back to the ViewPaper() event handler on the server side, how do I do that?
public void ViewPaper(object sender, EventArgs e)
{
}
My recommendation is to use a Repeater or a ListView control
Use a Repeater if the data will be used as read-only
Use a ListView if you want to page your results and/or allow the end user to perform CRUD operation over your data
For example, your code would look like this when using a Repeater and an ObjectDataSource controls:
ASPX
<asp:ObjectDataSource ID="ods" runat="server"
SelectMethod="GetQuestionPapers"
TypeName="Your_Namespace.PapersRepository">
</asp:ObjectDataSource>
<asp:Repeater runat="server" DataSourceID="ods" ID="r" OnItemCommand="r_ItemCommand">
<ItemTemplate>
<div style="border-bottom: 1px solid; padding-bottom:20px">
<asp:HiddenField runat="server" ID="paperID" Value='<%# Eval("PaperID") %>'/>
<asp:Label runat="server" ID="university" Text='<%# Eval("University") %>'/><br />
<asp:Label runat="server" ID="courseName" Text='<%# Eval("CourseName") %>'/>:<asp:Label runat="server" ID="courseCode " Text='<%# Eval("CourseCode ") %>'/><br />
<asp:Label runat="server" ID="paperType" Text='<%# Eval("Type") %>' /><br />
<asp:Label runat="server" ID="year" Text='<%# Eval("Year") %>' /><br />
<asp:Button ID="View_Paper" runat="server" Text="View Paper" CommandName="ViewPaperCommand"
/>
</div>
</ItemTemplate>
<SeparatorTemplate>
<hr />
</SeparatorTemplate>
</asp:Repeater>
ASPX code behind
protected void r_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "ViewPaperCommand":
var hidden = e.Item.FindControl("paperID") as HiddenField;
var myPaperID = hidden.Value;
break;
}
}
Papers repository class
namespace Your_Namespace
{
public class PapersRepository
{
public IEnumerable < QuestionPaper > GetQuestionPapers()
{
return QuestionPapers.AsEnumerable();
}
}
}
You could bind it to a control and then reference that control directly?
I know you have multiple questions papers being output, so that in itself is the issue. It's been a while since I have used webforms, but could you not use a repeater control which would give you a row context within which you could get the specific question paper id you are looking for?
Use a repeater. That kind of old skool ASP classic code has no place in ASP.Net projects. Here's an example: http://www.dotnetcurry.com/ShowArticle.aspx?ID=663
It is possible to customise a repeater to make a lightweight DataGrid or ListView equivalent too.

Asp.net buttons inside control inside gridview not working

I need to display a list of clients, but display them differently based on a parameter.
To do this, I have a gridvew, and inside there is a user control. That control has an "if" based on the type.
My problems:
If I add a button inside the control, when it is pressed I get a button validation error.
If I disable validation errors (enableEventValidation="false"), I get button commands to work, but I'm not able to change values on the control either with full postbacks or an updatepanel.
<asp:GridView ID="gvClients" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<xxx:ClientListGridItem ID="ClientListItem1" runat="server" Client='<%# ((Client) Container.DataItem) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
ClientListGridItem.ascx :
<% if (Client.Style >= 100)
{
%>
<div class="ClientListItem1">
...
<%
}
else
{
%>
<div class="ClientListItem2">
<asp:Button ID="Button2" runat="server" onclick="Button1_Click" Text="Button" />
...
<%
}
%>
I'm sure there is prettier, more object oriented way to do this too...
Changing ClientListGridItem.ascx into:
<asp:Panel id="Div1" CssClass="ClientListItem1" runat="server">
...
</asp:Panel>
<asp:Panel id="Div2" CssClass="ClientListItem2" runat="server">
<asp:Button ID="Button2" runat="server" onclick="Button1_Click" CausesValidation="false" Text="Button" />
..
</asp:Panel>
<script runat="server">
override void OnDataBinding(EventArgs e) {
Div1.Visible = Client.Style >= 100;
Div2.Visible = ! Div1.Visible;
}
</script>
should work.

Categories

Resources