Select an item in dropdownlist using jquery - c#

I am using the following to code to bind a dropdownlist using jquery
if ($("#status_input option[value='" + status + "']").length > 0) {
$('#status_input').val(status);
}
else {
$('#status_input').get(0).selectedIndex = -1;
}
in status i am getting "1", i am not getting any error, but not able to bind the dropdownliast as well as this stops the working code, means when i am commenting this code the reset information bind successfully but, when i am using this code, it does not throw any error as well as not binding the Results.
Please help me how can resolve this.
UPDATE::'
My HTML is::
<asp:Repeater ID="OffersRepeater" runat="server">
<ItemTemplate>
<div class="grid_row">
<div class="offer_id" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "OfferId") %>
</div>
<div class="offer_active" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "ActiveStatus")%>
</div>
<div class="offer_partner" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "Partner") %>
</div>
<div class="offer_description" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "Description") %>
</div>
<div class="offer_image" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "ImageSource") %>
</div>
<div class="offer_url" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "Url") %>
</div>
<div class="offer_url_text" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "UrlText") %>
</div>
<div class="offer_email" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "Email") %>
</div>
<div class="offer_phone" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "Phone") %>
</div>
<div class="offer_status" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "IsActive").ToString().ToLower()=="true" ? "1" : "0" %>
</div>
<div class="offer_approval_date" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "ApprovalDate") is DateTime ? ((DateTime)DataBinder.Eval(Container.DataItem, "ApprovalDate")).ToString( "MM-dd-yyyy") : "" %>
</div>
<div class="offer_start_date" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "StartDate") is DateTime ? ((DateTime)DataBinder.Eval(Container.DataItem, "StartDate")).ToString( "MM-dd-yyyy") : ""%>
</div>
<div class="offer_end_date" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "EndDate") is DateTime ? ((DateTime)DataBinder.Eval(Container.DataItem, "EndDate")).ToString( "MM-dd-yyyy") : ""%>
</div>
<div class="offer_legal" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "LegalInformation") %>
</div>
<div class="offer_twitter" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "Twitter") %>
</div>
<div class="offer_facebook" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "Facebook")%>
</div>
<div class="offer_legalonofferpage" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "LegalOnOfferPage")%>
</div>
<div class="offer_Season" style="display: none;">
<%# DataBinder.Eval(Container.DataItem, "Season")%>
</div>
<div class="grid_row_background" runat="server" id="RowBackground">
</div>
<div class="grid_row_foreground">
<div class="grid_cell" style="padding-left: 10px; width: 420px;">
<span class='<%# DataBinder.Eval(Container.DataItem, "ActiveStatus")%>'></span>
<%# DataBinder.Eval(Container.DataItem, "Partner") %>
</div>
<div class="grid_cell">
<a href="javascript:void(0)" onclick="ViewXmlOffer(this);" title="View Offer" class="icon_button view_icon">
</a>
<a href="javascript:void(0)" onclick="editOffer(this);" title="Edit Offer" class="icon_button edit_icon">
</a>
</div>
<div class="clear">
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
here is that DRPDOWN
<div class="box_foreground">
<div class="form_field_text" title="OFFER STATUS" style="width: 298px;">
OFFER STATUS</div>
<select id="status_input" class="form_input" style="width: 308px;">
<option value="1" selected="selected">ACTIVE</option>
<option value="0">DEACTIVATED</option>
</select>
</div>
MY JQUERY CODE IS ::
function editOffer(link) {
$('#offerEntryBox').data('offer', $(link).parents('.grid_row'));
$('#offerEntryBox').data('category', $(link).parents('.grid').parent());
alert('hi');
resetForm();
$('#offerListBox').fadeOut('fast', function () {
$('#offerEntryBox').fadeIn('fast'); doResize();
});
}
and the function in which i am facing problem is :: resetForm();
function resetForm() {
var partner = '', categoryID = '', url = '', urlText = '', email = '', phone = '', startDate = '', endDate = '', description = '', legal = '', image = '', twitter = '', facebook = '', status = '1', Season='';
var myOfferEditor = $find(offereditorname);
var myLegalEditor = $find(legaleditorname);
$('#Legendbox').css('display', 'none');
var offer = $('#offerEntryBox').data('offer');
if (offer != null && offer != undefined) {
$('#offerEntryBox').find('.form_title').text('EDIT OFFER');
partner = $(offer).children('.offer_partner').text();
url = $(offer).children('.offer_url').text();
urlText = $(offer).children('.offer_url_text').text();
email = $(offer).children('.offer_email').text();
phone = $(offer).children('.offer_phone').text();
startDate = $(offer).children('.offer_start_date').text();
endDate = $(offer).children('.offer_end_date').text();
description = $(offer).children('.offer_description').html();
legal = $(offer).children('.offer_legal').html();
image = $(offer).children('.offer_image').text();
status = $(offer).children('.offer_status').text();
twitter = $(offer).children('.offer_twitter').text();
facebook = $(offer).children('.offer_facebook').text();
Season = $(offer).children('.offer_Season').text();
}
else
$('#offerEntryBox').find('.form_title').text('NEW OFFER');
var category = $('#offerEntryBox').data('category');
if (category != null && category != undefined)
categoryID = $(category).children('.category_id').text();
$('#partner_input').val(partner);
$('#url_input').val(url);
$('#url_text_input').val(urlText);
$('#partner_email_input').val(email);
$('#phone_input').val(phone);
myOfferEditor.set_html(description);
myLegalEditor.set_html(legal);
$('#twitter_input').val(twitter);
$('#facebook_input').val(facebook);
alert(status);
// if ($('[id$=category_input option[value=22]').length > 0) {
// alert(categoryID);
// }
// if ($("#category_input option[value='" + categoryID + "']").length > 0) {
// $('#category_input').val(categoryID);
// alert('entered 1');
// }
// else {
// $('#category_input').get(0).selectedIndex = -1;
// alert('entered 2');
// }
if ($("#status_input option[value='" + status + "']").length > 0) {
$('#status_input').val(status);
}
else {
$('#status_input').get(0).selectedIndex = -1;
}
$('#start_date_input').val(startDate);
$('#end_date_input').val(endDate);
validateDate($('#start_date_input'));
validateDate($('#end_date_input'));
$('.form_input', '#submit_offer_form').not('select, #start_date_input, #end_date_input').each(function () {
$(this).siblings('.form_field_text').text($.trim(this.value) == '' ? $(this).siblings('.form_field_text').attr('title') : this.value);
});
$('select.form_input', '#submit_offer_form').each(function () {
$(this).css('display', 'none');
$(this).siblings('.form_field_text').text($.trim(this.value) == '' ? $(this).siblings('.form_field_text').attr('title') : $(this).children('option:selected').text())
});
$('#image_preview_container').children('img').remove();
if (image != '' && contentPath != undefined) {
$('#image_source_input').val(image);
loadPreview(contentPath, image, $('#image_preview_container'), 195, 98);
}
setBoxHighlight($('.form_field', '#submit_offer_form').add($('#image_source_input').parents('.form_part')), false);
$('.form_status_message').text('');
setFormInteraction(true);
}

I have resolved out the issue actually the value is containing the white space. that's why it didn't get the exact value. i have just trim the string value to resolve the issue.

Related

Repeater control with IF Else statement always reture true or false in aspx page

I need to show HTML based on the Container.ItemIndex % 2 ==0 condition
But for me it always return either true or false based on the coding in the code
<asp:Repeater ID="rptNews" runat="server" EnableViewState="False" OnItemDataBound="rptNews_ItemDataBound">
<ItemTemplate>
<div style="display:none;"><%# _repeaterIndex = Container.ItemIndex %></div>
<% if (_repeaterIndex % 2 == 0)
{%>
<div class="col-md-4 col-lg-3 col-sm-6 no-padding newslist-col">
<div class="blog-item style-3">
<div class="blog-image">
<img alt="image" class="img-responsive center-block" src='<%# Eval("Image") %>' />
</div>
<div class="blog-content">
<div class="text-center">
<h5 class="date"><%# getDate(Eval("Date")) %></h5>
<h3 class="title-news blog-title newslisttitle"><%# Eval("Heading") %></h3>
<a href='<%# getURL(Eval("ID")) %>'><strong> MORE </span></strong></a>
</div>
</div>
</div>
</div>
<% }
else
{ %>
<div class="col-md-4 col-lg-3 col-sm-6 no-padding newslist-col">
<div class="blog-item style-3">
<div class="blog-content content-top">
<div class="text-center">
<h5 class="date"><%# Eval("Date") %></h5>
<h3 class="title-news blog-title newslisttitle"><%# _repeaterIndex %> <%# Eval("Heading") %></h3>
<a href='<%# getURL(Eval("ID"),Eval("Heading")) %>'><strong> MORE </strong></a>
</div>
</div>
<div class="blog-image">
<img alt="image" class="img-responsive center-block" src='<%# Eval("Image") %>' />
</div>
</div>
</div>
<% } %>
</ItemTemplate>
</asp:Repeater>
CODE BEHIND
protected void rptNewsList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
_repeaterIndex = _repeaterIndex + 1;
if (e.Item.ItemIndex % 2 == 0)
{
_showTop = true;
}
else
{
_showTop = false;
}
}
}
By now i have tried several thing but it is not working properly if (_repeaterIndex % 2 == 0) this is always true or false based on teh total row count as in my case it always show the 13 as i have 13 records if i display for testing _repeaterIndex it show the the correct value but in if it always take the final value of Container.ItemIndex not the current value
<h3 class="title-news blog-title newslisttitle"><%# _repeaterIndex%> <%# Eval("Heading") %></h3>
What is the best way to solve this issue i am facing
Much easier would be to use Container.ItemIndex directly instead of using the ItemDataBound Event. You can do this by using two PlaceHolders and set their Visibility based on the value of ItemIndex.
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible='<%# Container.ItemIndex % 2 == 0 %>'>
Even content<br />
</asp:PlaceHolder>
<asp:PlaceHolder ID="PlaceHolder2" runat="server" Visible='<%# Container.ItemIndex % 2 == 1 %>'>
Odd content<br />
</asp:PlaceHolder>
</ItemTemplate>
After spending hours trying to find other-ways of solving this issue i finally used two Panel and i hide & show based on the e.Item.ItemIndex % 2 == 0 value in teh code behind. I thing this is the most effective way of doing it.
<asp:Repeater ID="rptNewsList" runat="server" EnableViewState="False" OnItemDataBound="rptNewsList_ItemDataBound">
<ItemTemplate>
***HTML WILL GO HERE
<asp:Panel runat="server" ID="PanelTopImage" CssClass="col-md-4 col-lg-3 col-sm-6 no-padding newslist-col">
</asp:Panel>
<asp:Panel runat="server" ID="PanelBottomImage" CssClass="col-md-4 col-lg-3 col-sm-6 no-padding newslist-col">
***HTML WILL GO HERE
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
CODE BEHIND
protected void rptNewsList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Panel pnlTopImage = e.Item.FindControl("PanelTopImage") as Panel;
Panel pnlBottomImage = e.Item.FindControl("PanelBottomImage") as Panel;
if (e.Item.ItemIndex % 2 == 0)
{
pnlTopImage.Visible = true;
pnlBottomImage.Visible = false;
}
else
{
pnlTopImage.Visible = false;
pnlBottomImage.Visible = true;
}
}
}

Bootstrap Carousel with Repeater shows all slides one by one i want to display it 3 items by one

I am using Bootstrap carousel slider script inside Repeater but its not working proper.I have projects database table i want to display this projects in slide 3 project by one slider each slide has 3 project . my code display one project per slide i don't know how to make it please help me .
Each slide : 1 2 3 then second one 4 5 6 at the same row with slider
this link has the same slide i want slider i want like it
<!-- Begin Carousel -->
<div class="row">
<div id="realto-carousel-afee" class="carousel slide">
<div class="carousel-navigation pull-right"> <a class="serif italic pull-left view-all-carousel" href="properties-grid-layout-2">All</a> <a class="left carousel-control pull-left" href="#realto-carousel-afee" data-slide="prev"><i class="fa fa-angle-left"></i></a> <a class="right carousel-control pull-right" href="#realto-carousel-afee" data-slide="next"><i class="fa fa-angle-right"></i></a> </div>
<div class="carousel-inner">
<asp:Repeater runat="server" ID="ProjectsRepater">
<ItemTemplate>
<div <%# Container.ItemIndex == 0 ? "class=\"item active\"" : "class=\"item\"" %>>
<div class="col-lg-4 col-md-4 col-sm-4 col-sx-12">
<div class="box-container">
<div class="holder"> <a class="overlay" href="" title=""> <span class="more"> <i class="fa fa-zoom-in"></i> </span>
<div class="prop_img"> <img width="370" height="210" src="150w" sizes="(max-width: 370px) 100vw, 370px" /> </div>
</a> <span class="prop-tag"></span>
<div class="prop-info">
<h3 class="prop-title">
<asp:Label ID="ProjId" runat="server" Visible="false" Text='<%# Eval("ID")%>'></asp:Label>
<asp:Label Text='<%# Eval("ProjectName")%>' ID="lblProjName" runat="server"></asp:Label>
</h3>
<ul class="more-info clearfix">
<li class="info-label clearfix"> <span class="pull-left" style="float:right !important"></span>
<label id="lblArea" runat="server" class="qty pull-right">2</label>
</li>
<li class="info-label clearfix"> <span class="pull-left" style="float:right !important"></span> <span id="lblPaymentsSystem" runat="server" class="qty pull-right">2</span> </li>
<li class="info-label clearfix"> <span class="pull-left" style="float:right !important"></span> <span id="lblReceivedDate" runat="server" class="qty pull-right">2</span> </li>
</ul>
</div>
<!-- prop-info -->
</div>
<!-- holder -->
</div>
<!-- box-container -->
</div>
</div>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
// RepeterData();
ProjectsRepater.DataSource = GetAllProjecct();
ProjectsRepater.DataBind();
}
public class Proj
{
public int ID { get; set; }
public string ProjectName { get; set; }
}
public List<Proj> GetAllProjecct()
{
List<Proj> listproj = new List<Proj>();
SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings ["AlamarConnectionString"].ConnectionString);
SqlCommand com = new SqlCommand("Select ID,ProjectName from Projects", con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
Proj cnt = new Proj();
cnt.ID = Convert.ToInt32(reader["ID"]);
cnt.ProjectName = Convert.ToString(reader["ProjectName"]);
listproj.Add(cnt);
}
return listproj;
}
See this codepen, I think this will solve your problem
HTML
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<div class="item active">
<div class="container">
<div class="row">
<div class="col-xs-4">
<div class="slide slide1">slide 1 content here</div>
</div>
<div class="col-xs-4">
<div class="slide slide2">slide 2 content here</div>
</div>
<div class="col-xs-4">
<div class="slide slide3">slide 3 content here</div>
</div>
</div>
</div>
</div>
<div class="item">
<div class="container">
<div class="row">
<div class="col-xs-4">
<div class="slide slide4">slide 4 content here</div>
</div>
<div class="col-xs-4">
<div class="slide slide5">slide 5 content here</div>
</div>
<div class="col-xs-4">
<div class="slide slide6">slide 6 content here</div>
</div>
</div>
</div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
CSS
.slide {
height: 200px;
color: #fff;
font-size: 20px;
}
.slide1 {
background: red;
}
.slide2 {
background: yellow;
}
.slide3 {
background: blue;
}
.slide4 {
background: orange;
}
.slide5 {
background: green;
}
.slide6 {
background: violet;
}
http://codepen.io/Arshmeet/pen/BQKrOb
Follow a complete example of carousel that calls ajax in controller to populate 3 slides. I call just 1 record each calling for better performance but you can change.
View:
<div class="carousel slide" id="main-slide" data-ride="carousel">
<ol class="carousel-indicators text-center">
<li data-target="#main-slide" data-slide-to="0" class="active"></li>
<li data-target="#main-slide" data-slide-to="1"></li>
<li data-target="#main-slide" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<a href="" id="home1-link1">
<img id="home1-imagem1" alt="" title="" src="" width="20" height="20" class="img-responsive center-block">
<div class="carousel-caption" id="home1-caption1"><div id="home1-legenda1"></div></div>
</a>
</div>
<div class="item">
<a href="" id="home1-link2">
<img id="home1-imagem2" alt="" title="" src="" width="20" height="20" class="img-responsive center-block">
<div class="carousel-caption" id="home1-caption2"><div id="home1-legenda2"></div></div>
</a>
</div>
<div class="item">
<a href="" id="home1-link3">
<img id="home1-imagem3" alt="" title="" src="" width="20" height="20" class="img-responsive center-block">
<div class="carousel-caption" id="home1-caption3"><div id="home1-legenda3"></div></div>
</a>
</div>
</div>
<div class="slides-control">
<a title="Imagem Anterior" id="tras-home1-slide" class="carousel-control" href="#main-slide" data-slide="prev">
<i class="fa fa-angle-left"></i></a>
<a title="Imagem Posterior" id="frente-home1-slide" class="direita carousel-control" href="#main-slide" data-slide="next">
<i class="fa fa-angle-right"></i></a>
</div>
</div>
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
var nrReg = 0;
var pag = "";
var i = 1;
var selecaoJquery = "";
var removeuTerceiroSlide = false;
function slide1() {
$.ajax({
url: "/Image/Slide",
type: "POST",
data: { "nrRegistro": nrReg },
ifModified: true,
cache: true,
async: true,
dataType: "json",
success: function (data) {
if (i == 2 && data.length == 0) {
$("#item-main-slide3").remove();
$("#carousel-indicator3").remove();
removeuTerceiroSlide = true;
return;
}
else if (i == 3 && data.length == 0) {
$("#item-main-slide3").remove();
$("#carousel-indicator3").remove();
if (removeuTerceiroSlide == true) {
$("#item-main-slide2").remove();
$("#carousel-indicator2").remove();
}
return;
}
if (i > 1) {
selecaoJquery = "#carousel-indicator" + i;
$(selecaoJquery).show();
}
selecaoJquery = '#home1-legenda' + i;
$(selecaoJquery).html(data[0].DescricaoLegenda);
selecaoJquery = '#home1-link' + i;
if (data[0].URLPagina == null) {
$(selecaoJquery).attr('href', '/lista/produtos');
}
else {
$(selecaoJquery).attr('href', '/produto/' + data[0].URLPagina);
}
selecaoJquery = '#home1-imagem' + i;
$(selecaoJquery).attr("src", data[0].EnderecoImagem).attr("title", data[0].Descricao)
.attr("alt", data[0].DescricaoAlternativa).attr("width", data[0].Largura).attr("height", data[0].Altura);
selecaoJquery = '#home1-caption' + i;
$(selecaoJquery).css('background-color', data[0].CorFundoLegenda);
i++;
}
});
};
nrReg = 1;
slide1();
nrReg = 2;
setTimeout(slide1(), 400);
nrReg = 3;
setTimeout(slide1(), 900);
$('#main-slide').carousel({ interval: 6000 });
});
</script>
}
Controller (/Image/Slide):
[HttpPost]
public async Task<JsonResult> Slide(int nrRegistro)
{
var recs = (from d in db.Imagem
where d.IdPostagemImagem == 1 &&
d.EnderecoImagem.Length > 0
orderby d.IdImagem
select new
{
d.IdImagem,
d.DescricaoLegenda,
d.EnderecoImagem,
d.CorFundoLegenda,
d.CorFundoLegendaMobile,
d.Descricao,
d.Largura,
d.Altura,
d.DescricaoAlternativa,
d.PosicaoHorizontalLegenda,
d.Produto.URLPagina
});
if (nrRegistro > 1)
{
nrRegistro--;
recs = recs.Skip(nrRegistro).Take(1);
}
else
recs= recs.Take(1);
return Json( await recs.ToListAsync());
}

how to create html using foreach loop

I have an aspx form which has the following code
<div class="media packagesList">
<a class="media-left fancybox-pop" href="img/packages/package-list-01.png">
<asp:Image ID="imgThumbnail" runat="server" CssClass="media-object" />
</a>
<div class="media-body">
<div class="bodyLeft">
<h4 class="media-heading">
<a href="javascript.void(0)">
<asp:Label ID="lblHeading" runat="server"></asp:Label>
</a>
</h4>
<div class="countryRating">
<span>
<asp:Label ID="lblLocation" runat="server"></asp:Label>
</span>
<ul class="list-inline rating">
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
</ul>
</div>
<p>
<asp:Label ID="lblDescription" runat="server"></asp:Label>
</p>
<ul class="list-inline detailsBtn">
<li><span class="textInfo"><i class="fa fa-calendar" aria-hidden="true"></i>
<asp:Label ID="lblDate" runat="server"></asp:Label></span></li>
<li><span class="textInfo"><i class="fa fa-clock-o" aria-hidden="true"></i>
<asp:Label ID="lblDays" runat="server"></asp:Label></span></li>
</ul>
</div>
<div class="bodyRight">
<div class="bookingDetails">
<h2>
<asp:Label ID="lblPrice" runat="server"></asp:Label></h2>
<p>Per Person</p>
Details
<a class="btn buttonTransparent" data-toggle="modal" href='.html'>Inquiry</a>
</div>
</div>
</div>
</div>
And the output is this?
Please help me understand how to do this dynamically so I only have to write the code once and all the tours in the database will show in my tours page.
You can write codes in pages of asp.net by using
<% //code %>
Or
<% =data ℅>
You can also split the code
<% foreach(var x in values) { %>
<div>hello <%= x.name %></div>
<% } %>
Or in razor engine web pages
#code
And
#{ //code }
EDIT:Added
for your example lets say that you have this class that present a tour:
public class Tour{
public string ImageUrl {get;set;}
public string Title {get;set;}
public string Text {get; set; }
}
and you have a list of tours:
var tours=new List<Tour>();
tours.Add(new Tour()
{
ImageUrl="img.png",
Title="Hello World",
Text="This Is The Body Text"
});
tours.Add(new Tour()
{
ImageUrl="img2.png",
Title="Tour two",
Text="This Is The Body Text2"
});
in this case in a normal console code you would Enumerate the values using this for each:
foreach(var item in tours){
console.WriteLine(item.Title)//Display the title in console
}
let's change the console code to a web forms code:
<% foreach(var item in tours){ %>
<!-- using HTML -->
<div>
<img src="<%= item.ImageUrl %>" alt="Image" />
<span>
<%= item.Title %><!--The title from the tour -->
</span>
<p>
<%= item.Text %><!--The tour body -->
</p>
</div>
<% } %>
Hope this Helped.
Edit:Example
Here is the full Default.aspx.cs code:
public partial class _Default : Page
{
protected IList<Tour> tours;
protected void Page_Load(object sender, EventArgs e)
{
tours= new List<Tour>();
tours.Add(new Tour()
{
ImageUrl = "img.png",
Title = "Hello World",
Text = "This Is The Body Text"
});
tours.Add(new Tour()
{
ImageUrl = "img2.png",
Title = "Tour two",
Text = "This Is The Body Text2"
});
}
}
public class Tour
{
public string ImageUrl { get; internal set; }
public string test { get; set; }
public string Text { get; internal set; }
public string Title { get; internal set; }
}
In this example i created a list of Tour Seed it with values on Page_Load
thin you can access it form the web page code:
<% foreach(var item in tours){ %>
<!-- using HTML -->
<div>
<img src="<%= item.ImageUrl %>" alt="Image" />
<h2>
<%= item.Title %><!--The title from the tour -->
</h2>
<p>
<%= item.Text %><!--The tour body -->
</p>
</div>
<% } %>
Also this is a duplicated question of How to loop through data in web forms
Use repeator control in ASP.Net
https://msdn.microsoft.com/en-us/library/zzx23804(v=vs.85).aspx

Page Loading Multiple times

Having a unusual problem with an application I'm building, so what I'm looking to do is a user can view preview of their adverts they have created, click the advert which is a dynamic link and be brought to a new page which will show the advert in more detail. The more detail page is then runs a to check the query string, pass the parameters of the query sting to a method which pulls the correct details form the database. This part works perfectly, but when the object is returned the pages loads again, calls the same method 3 times, but with null parameters which in returns a null reference to an object that doesn't exist.
I've tried to refactor the code so when a page loads it won't retrieve form the database unless the search parameters are valid. When the page loads, components won't work then, for example the Image Carousel.
I've tried hard coding the parameters into the method, will work perfectly. will only load once.
I've created two new pages which do not inherit form a master page and used the exact same methods. works perfectly. I tried the method on a two different pages that are inherited form the master page and same problem.
Detailed Page.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeFile="DetailAdvert.aspx.cs" Inherits="Lenders.ie.DetailAdvert" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="col-lg-9">
<div class="container">
<div class="row">
<!--Advert Image -->
<div class="container">
<div class="row">
<!-- Carosel goes here -->
<div class="row carousel-holder">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-10">
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<img class="slide-image" id="Img1" runat="server" src="http://placehold.it/800x380" alt=""/>
</div>
<div class="item">
<img class="slide-image" id="Img2" runat="server" src="http://placehold.it/800x380" alt=""/>
</div>
<div class="item">
<img class="slide-image" id="Img3" runat="server" src="http://placehold.it/800x380" alt=""/>
</div>
</div>
<a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
</div>
</div>
</div>
</div>
<!--User Details-->
<br />
<div class="container">
<div class="row">
<!-- Descriptin and profile view -->
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-5">
<div class="well well-sm">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<img src="" runat="server" id="imgProfilePic" alt="" class="img-rounded img-responsive" />
</div>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<h4>
<asp:Label ID="lblFristName" runat="server" Text=""></asp:Label>
<asp:Label ID="lblSecondName" runat="server" Text=""></asp:Label>
</h4>
<small><cite title="Location"><asp:Label ID="lblLocation" runat="server" Text=""></asp:Label> <i class="glyphicon glyphicon-map-marker">
</i></cite></small>
<p>
<i title="Email" class="glyphicon glyphicon-envelope"></i> <asp:Label ID="lblEmail" runat="server" Text=""></asp:Label>
<br />
<i title="Join Date" class="glyphicon glyphicon-user"></i> <asp:Label ID="lblJoinDate" runat="server" Text=""></asp:Label><br />
<i title="User Rating" class="glyphicon glyphicon-stats"> </i><asp:Label ID="lblUserRating" runat="server" Text=""></asp:Label><br />
<i title="Contact Number" class="glyphicon glyphicon-phone"> </i><asp:Label ID="lblContactNumber" runat="server" Text=""></asp:Label>
</p>
<!-- Split button -->
<asp:Button ID="btnMessage" runat="server" Text="Message" CssClass="btn btn-success" />
</div>
</div>
</div>
</div>
<!-- Description / Product Details-->
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-5">
<div class="well well-sm">
<h4> Description: </h4>
<p>
<asp:Label ID="lblDesc" runat="server" Text=""></asp:Label>
</p>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<!-- Comment Section -->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-10">
<div class="well well-sm">
<h4>Comments</h4>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
</asp:Content>
Detailed Aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using DataModels;
namespace Lenders.ie
{
public partial class DetailAdvert : System.Web.UI.Page
{
public Advert_User ReturnedUserAdvet = new Advert_User();
public BalAdvertManger BALMan = new BalAdvertManger();
protected void Page_Load(object sender, EventArgs e)
{
//Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.ExpiresAbsolute = DateTime.Now.AddMonths(-1);
//GetData();
//PopulatePage();
//int UserID = Convert.ToInt32(Request.QueryString["UiD"]);
//int AdvertID = Convert.ToInt32(Request.QueryString["AdID"]);
if (!Page.IsPostBack)
{
GetData();
}
}
public void GetData()
{
//int UserID = 41;
//int AdvertID = 2;
int UserID = Convert.ToInt16(Request.QueryString["UiD"]);
int AdvertID = Convert.ToInt16(Request.QueryString["AdID"]);
if (UserID != 0 || AdvertID != 0)
{
ReturnedUserAdvet = BALMan.ReturnDetailedAdvert(UserID, AdvertID);
PopulatePage();
}
//int UserID = Convert.ToInt32(Request.QueryString["UiD"]);
//int AdvertID = Convert.ToInt32(Request.QueryString["AdID"]);
//int UserID = 41;
//int AdvertID = 2;
//ReturnedUserAdvet = BALMan.ReturnDetailedAdvert(UserID,AdvertID);
}
public void PopulatePage()
{
}
}
}
This is where the link is and directs to the Detailed page.
Profile Page.aspx
<%# Page Title="" Language="C#" EnableEventValidation="false" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="ProfilePage.aspx.cs" Inherits="Lenders.ie.ProfilePage1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="container">
<div class="row">
<%-- Adverts View--%>
<asp:View ID="AdvertsView" runat="server">
<h2>Adverts</h2>
</asp:View>
<%-- View Adverts --%>
<asp:View ID="View_ViewAdverts" runat="server">
<h2>View Adverts</h2>
<div class="row">
<asp:Literal ID="Advert1" runat="server"></asp:Literal>
<asp:LinkButton ID="LinkButton1" OnClick="LinkButton1_Click" runat="server">LinkButton</asp:LinkButton>
</div>
</asp:View>
<%--There was three closing divs here--%>
<asp:View ID="MessageView" runat="server">
<h2>Messages</h2>
</asp:View>
</asp:MultiView>
</div>
</div>
</div>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
ProfilePage aspx.cs - Method that creates the link
public void DisplayUserAdverts()
{
int UserID = Convert.ToInt32(Session["UserID"]);
int i = 0;
ListOfUserAdverts = BalAdvertManager.ReturnUserAdvert(UserID);
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
foreach (Advert item in ListOfUserAdverts)
{
string ColDiv = "col-sm-4 col-lg-4 col-md-4";
string ThumbClass = "thumbnail";
string Image = "AdvertThumbnails/" + item.Img1.ToString();
string Caption = "caption";
string Link = "DetailAdvert.aspx/?AdID=" + item.AdvertID.ToString() + "&UiD=" + item.UserID.ToString();
Button btn = new Button();
writer.AddAttribute(HtmlTextWriterAttribute.Class, ColDiv);
writer.RenderBeginTag(HtmlTextWriterTag.Div);
writer.AddAttribute(HtmlTextWriterAttribute.Class, ThumbClass);
writer.RenderBeginTag(HtmlTextWriterTag.Div);
//writer.AddAttribute(HtmlTextWriterAttribute.Src, Image);
writer.AddAttribute(HtmlTextWriterAttribute.Href, Link);
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.AddAttribute(HtmlTextWriterAttribute.Src, Image);
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag();
writer.RenderEndTag();
writer.AddAttribute(HtmlTextWriterAttribute.Class, Caption);
writer.RenderBeginTag(HtmlTextWriterTag.Div);
//writer.AddAttribute(HtmlTextWriterAttribute.Src, Image);
//writer.RenderBeginTag(HtmlTextWriterTag.Div);
//writer.AddAttribute(HtmlTextWriterAttribute.Class, Caption);
writer.RenderBeginTag("h4");
writer.Write(item.Title.ToString());
writer.RenderEndTag();
writer.RenderBeginTag("p");
//Does Something
writer.Write(item.Desc.ToString().Substring(0, 50));
writer.Write("</br>");
writer.Write("Testing" + i.ToString());
writer.Write("</br>");
this.Controls.Add(btn);
writer.AddAttribute(HtmlTextWriterAttribute.Href, Link);
// writer.AddAttribute(HtmlTextWriterAttribute.Id);
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write("Link");
writer.RenderEndTag();
writer.RenderEndTag();
//writer.WriteBeginTag("p");
// // Does Something
//writer.WriteEndTag("p");
writer.RenderEndTag();
writer.RenderEndTag();
writer.RenderEndTag();
i++;
}
}
Advert1.Text = stringWriter.ToString();
}
Master Page.aspx
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs" Inherits="Lenders.ie.MasterPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Shop Homepage - Start Bootstrap Template</title>
<!-- Bootstrap Core Content -->
<link href="Content/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="Content/shop-homepage.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<form id="form1" runat="server">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<%-- <a class="navbar-brand" href="www.google.com">
</a>--%>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<asp:HyperLink ID="Home" runat="server">Home</asp:HyperLink>
</li>
<li>
<asp:HyperLink ID="Services" runat="server">Services</asp:HyperLink>
</li>
<li>
<asp:HyperLink ID="Contact" runat="server">Contact</asp:HyperLink>
</li>
<li>
<asp:HyperLink ID="Login" runat="server">Log In</asp:HyperLink>
</li>
</ul>
<div class="navbar-form navbar-right">
<div class="input-group input-sm">
<asp:TextBox ID="txtSearch" runat="server" CssClass="form-control form-control-sm " AutoPostBack="true"></asp:TextBox>
<span class="
</span>
</div>
</div>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<div class="container">
<div class="row">
<div class="col-md-3">
<p class="lead">Shop Name</p>
<div class="list-group">
<asp:HyperLink ID="HyperLink1" CssClass="list-group-item" runat="server">Sports</asp:HyperLink>
<asp:HyperLink ID="HyperLink2" CssClass="list-group-item" runat="server">Hobbies</asp:HyperLink>
<asp:HyperLink ID="HyperLink3" CssClass="list-group-item" runat="server">Life Style</asp:HyperLink>
<asp:HyperLink ID="HyperLink4" CssClass="list-group-item" runat="server">Another Example</asp:HyperLink>
<asp:HyperLink ID="HyperLink5" CssClass="list-group-item" runat="server"> Blah </asp:HyperLink>
</div>
</div>
<%-- <div class="col-md-9">
<div class="row carousel-holder">
<div class="col-md-12">--%>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
</asp:ContentPlaceHolder>
</div>
</div>
<%-- </div>
</div>
</div>--%>
<div class="container">
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © Your Website 2014</p>
</div>
</div>
</footer>
</div>
<!-- /.container -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>enter code here
</form>
</body>
</html>
Master Page.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Lenders.ie
{
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}

DNN LinkButton OnClick event not firing (using asp.net, C#)

I have a page that I would like to display a calendar of events that is stored in a MySQL database. I am pulling the events using asp:SqlDataSource and asp:Repeater. I am able to pull the events but I can't get the events to be sorted into the specific day. I"m using a asp:LinkButton with an OnClick event handler, but it doesn't seem to be firing when the LinkButton is clicked. I have included my code below. Any help on what i'm doing wrong and why my OnClick event isn't firing will be greatly appreciated./
ascx - page
<div class="Calendar_Container">
<ul class="Calendar_Tabs">
<li><asp:LinkButton runat="server" Text="All<br /> Week" OnClick="ShowEvents" CommandArgument="9"></asp:LinkButton></li>
<li class="Calendar_Active"><asp:LinkButton runat="server" Text="Sun<br />Nov 1" OnClick="ShowEvents" CommandArgument="1"></asp:LinkButton></li>
<li><asp:LinkButton runat="server" Text="Fri<br />Nov 6" OnClick="ShowEvents" CommandArgument="6"></asp:LinkButton></li>
</ul>
</div>
<div class="Calendar_Content">
<div id="Calendar_AllWeek" class="Calendar_Tab">
<asp:SqlDataSource runat="server" ID="sqlGetEventsAllWeek" />
<asp:Repeater runat="server" ID="rptGetEventsAllWeek" DataSourceID="sqlGetEventsAllWeek">
<ItemTemplate>
<div class="Calendar_Item">
<div class="Calendar_ItemInfo">
<div class="Calendar_ItemTitle">
<h4><a href='<%# Eval("link") %>'><%# Eval("title") %></a></h4><br />
<strong><%# Eval("event_start_time") %> <%# Eval("event_end_time") %><br /><%# Eval("event_location") %></strong><br /></div>
<div class="Calendar_ItemDescription">
<p><%#System.Web.HttpUtility.HtmlDecode(Eval("description").ToString()) %><br />
<%# Eval("event_day") %>
</p>
</div>
</div>
<div class="clear_float"> </div>
</div>
</ItemTemplate>
<SeparatorTemplate><hr /></SeparatorTemplate>
</asp:Repeater>
</div>
<div id="Calendar_EventsSun" class="Calendar_Tab">
<asp:SqlDataSource runat="server" ID="sqlGetEventSun" />
<asp:Repeater runat="server" ID="rptGetEventSun" DataSourceID="sqlGetEventSun">
<ItemTemplate>
<div class="Calendar_Item">
<div class="Calendar_ItemInfo">
<div class="Calendar_ItemTitle">
<h4><a href='<%# Eval("link") %>'><%# Eval("title") %></a></h4><br />
<strong><%# Eval("event_start_time") %> <%# Eval("event_end_time") %><br /><%# Eval("event_location") %></strong><br /></div>
<div class="Calendar_ItemDescription">
<p><%# System.Web.HttpUtility.HtmlDecode(Eval("description").ToString()) %>
<br /><strong><%# Eval("event_day") %></strong>
</p>
</div>
</div>
<div class="clear_float"> </div>
</div>
</ItemTemplate>
<SeparatorTemplate><hr /></SeparatorTemplate>
</asp:Repeater>
</div>
<div id="Calendar_EventsFri" class="Calendar_Tab">
<asp:SqlDataSource runat="server" ID="sqlGetEventFri" />
<asp:Repeater runat="server" ID="rptGetEventFri" DataSourceID="sqlGetEventFri">
<ItemTemplate>
<div class="Calendar_Item">
<div class="Calendar_ItemInfo">
<div class="Calendar_ItemTitle">
<h4><a href='<%# Eval("link") %>'><%# Eval("title") %></a></h4>
<strong><%# Eval("event_start_time") %> <%# Eval("event_end_time") %><br /><%# Eval("event_location") %></strong><br />
</div>
<div class="Calendar_ItemDescription">
<p><%# System.Web.HttpUtility.HtmlDecode(Eval("description").ToString()) %>
<br /><strong><%# Eval("event_day") %></strong>
</p>
</div>
</div>
<div class="clear_float"> </div>
</div>
</ItemTemplate>
<SeparatorTemplate><hr /></SeparatorTemplate>
</asp:Repeater>
</div>
</div>
ascx.cs - code behind
namespace Christoc.Modules.Calendar {
public partial class View : CalendarModuleBase, IActionable
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
GetAllWeek("9");
GetHomecomingWeekSun("1");
GetHomecomingWeekFri("6");
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
protected void ShowEvents(object sender, EventArgs e)
{
string dayId = ((LinkButton)sender).CommandArgument;
GetAllWeek(dayId);
GetHomecomingWeekSun(dayId);
GetHomecomingWeekFri(dayId);
}
private void GetAllWeek(string dayId)
{
sqlGetEventsAllWeek.ConnectionString = stampConnStr;
sqlGetEventsAllWeek.ProviderName = stampProvName;
sqlGetEventsAllWeek.SelectCommand = string.Format(#"
SELECT *
FROM homecoming_program
WHERE event_day = ?
ORDER BY event_day DESC;");
sqlGetEventsAllWeek.SelectParameters.Clear();
sqlGetEventsAllWeek.SelectParameters.Add(#"day_id", dayId);
rptGetEventsAllWeek.DataBind();
}
private void GetHomecomingWeekSun(string dayId)
{
sqlGetEventSun.ConnectionString = stampConnStr;
sqlGetEventSun.ProviderName = stampProvName;
sqlGetEventSun.SelectCommand = string.Format(#"
SELECT *
FROM homecoming_program
WHERE event_day = ?
ORDER BY event_day DESC;");
sqlGetEventSun.SelectParameters.Clear();
sqlGetEventSun.SelectParameters.Add(#"day_id", dayId);
rptGetEventSun.DataBind();
}
private void GetHomecomingWeekFri(string dayId)
{
sqlGetEventFri.ConnectionString = stampConnStr;
sqlGetEventFri.ProviderName = stampProvName;
sqlGetEventFri.SelectCommand = string.Format(#"
SELECT *
FROM homecoming_program
WHERE event_day = ?
ORDER BY event_day DESC;");
sqlGetEventFri.SelectParameters.Clear();
sqlGetEventFri.SelectParameters.Add(#"day_id", dayId);
rptGetEventFri.DataBind();
}
}
}

Categories

Resources