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
Related
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());
}
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)
{
}
}
}
I'm getting this error, but I just can't tell where it might be coming from. The line that the error page is referencing is:
# Page Title="" Language="C#" MasterPageFile="~/CV.Master" AutoEventWireup="true" CodeBehind="AddPost.aspx.cs" Inherits="CV_Blog_WDW.AddPost"
But I can't see how that line can cause that error? Unless there's something I'm missing?
My .aspx code is:
<%# Page Title="" Language="C#" MasterPageFile="~/CV.Master" AutoEventWireup="true" CodeBehind="AddPost.aspx.cs" Inherits="CV_Blog_WDW.AddPost" %>
<asp:Content ID="Content1"
ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
<!-- =========
Special Nav for BLog page
===================================-->
<nav class="nav-blog">
<a href="default.aspx"
class="btn btn-left"
data-toggle="tooltip"
data-placement="left"
title=""
data-original-title="Home">
<i class="fa fa-home"></i>
</a>
<a href="#"
class="btn btn-big-blog">Blog</a>
<a href="#"
class="btn btn-right"
data-toggle="tooltip"
data-placement="right"
title=""
data-original-title="Reload Page">
<i class="fa fa-refresh"></i>
</a>
</nav>
<!-- =========
Start Show Yor Name Section
===================================-->
</div>
</header>
<!-- =========
End portrait section
===================================-->
<!-- =========
Start Content section
===================================-->
<section class="content open"
id="main-content">
<div class="body-content"
id="blog">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="blog-posts">
<div class="blog-post">
<h3 class="title with-icon">
<span class="fa fa-comment-o icn-title"></span> Add A Post
</h3>
<div class="box-block">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Title">Title</label>
<asp:TextBox ID="Title"
runat="server"
CssClass="form-control"></asp:TextBox>
</div>
<div class="form-group">
<label for="FeaturedImage">Featured Image</label>
<asp:FileUpload ID="FeaturedImage"
runat="server"
CssClass="form-control" />
</div>
</div>
</div>
<div class="form-group">
<label for="MesageForm">Body</label>
<asp:TextBox ID="Body"
TextMode="MultiLine"
Rows="8"
runat="server"
CssClass="form-control"></asp:TextBox>
</div>
<asp:Button id="btnAdd"
runat="server"
CssClass="btn btn-flat btn-lg"
Text="Add Post"
OnClick="btnAdd_Click" />
</div>
</div>
</div>
</div>
</div>
</div>
</asp:Content>
And my code behind is:
public partial class AddPost : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if(FeaturedImage.HasFile)
{
try
{
string filename = Path.GetFileName(FeaturedImage.FileName);
FeaturedImage.SaveAs(Server.MapPath("~/assets/images/blog/") + filename);
}
catch(Exception ex)
{
string error = ex.Message;
}
}
try
{
string connection = WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("AddPost", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Title", Title.Text);
cmd.Parameters.AddWithValue("#Date", DateTime.Now);
cmd.Parameters.AddWithValue("#FeatureImage", Path.GetFileName(FeaturedImage.FileName));
cmd.Parameters.AddWithValue("#PostedBy", 1);
cmd.Parameters.AddWithValue("#Body", Body.Text);
con.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
}
}
}
I've google'ed the error but there's nothing that seems relevant to my code? Really stumped on this one, not been able to try any fixes as to be honest not sure where to start. As far as I can see I'm not making a conversion, but maybe there's one going on that I'm, not aware of?
The error comes from assigning a string to a TextBox variable. The usual reason is that one forgets the Text property, and use something like:
MyTextbox = "Some string";
intead of:
MyTextbox.Text = "Some string";
However, as there is no such code in your methods, and because the error message points to the aspx page, the error is somewhere in the code that is generated from the markup.
You have a text box named Title. There is already a string property by that name in the Page class, and when the generated code tries to set the string property, the assigment will use the TextBox field instead as it shadows the string property.
Rename the Title text box to something that isn't used already.
I need to throw anywhere from 2 elements and up into an array that I can then jQuery.Ajax post to my MVC controller.
My issue is how to put them into an acceptable array or object that I can then pass to the MVC partial view?
I have classes setup I think will work for the buttons and jQuery btnMoveUp, btnMoveDown
I need to pass the data-procedureid and data-sortid to my MVC controller.
And for bonus points another part I think I will be stuck on. If they click the "Move Up" button. I need to grab the element above it and switch their sort orders. Or the "Move Down" button need to grab the element below it and switch their sort orders.
I'm hoping this will be as easy as jQuery(".btnMoveDown").next(".btnMoveDown").attr("data-sortorder") but i haven't tested this possibility.
Here is my future aJax:
$(".btnMoveUp").click(function () {
var currSortOrder = jQuery(this).data('sortorder');
// find the element above this one and grab the sort order
// switch the sort orders
$.ajax({
url: "YourController/GetData",
type: "get",
data: // What can I pass here that my MVC partial view can then use?
success: function (result) {
$("#procedures").html(result);
}
});
}
Here is the code:
<ul class="commentlist">
#{
int i = 1;
//foreach (var item in #Model.IPACS_Processes.IPACS_Procedures)
foreach (var item in #Model.IPACS_Procedures)
{
<li class="span6">
<img src="../../Images/thumbs/doc.png" alt="" class="pull-left" />
<div class="comment-info">
<h4>
<a href="#Url.Action("ViewProcedure", new { id = item.procedureID })">
#item.name</a></h4>
<h5>
<small>Owner: </small>#item.owner</h5>
<br />
<p>
#item.description
</p>
<br />
<p>
#if (i > 1)
{
<a href="javascript:void(0);" class="btn btn-small btnMoveUp" data-procedureid="#item.procedureID" data-sortorder="#i"><span class="iconfa-double-angle-up icon-white">
</span>Move Up</a>
}
#if (i < #Model.IPACS_Procedures.Count)
{
<a href="javascript:void(0);" class="btn btn-small btnMoveDown" data-procedureid="#item.procedureID" data-sortorder="#i"><span class="iconfa-double-angle-down">
</span>Move Down</a>
}
#{i++;}
</p>
</div>
</li>
<br style="clear: both;" />
}
}
</ul>
Here it is generated:
<ul class="commentlist">
<li class="span6">
<img src="../../Images/thumbs/doc.png" alt="" class="pull-left">
<div class="comment-info">
<h4>
<a href="/MasterList/ViewProcedure/123">
XYZ Process Server</a></h4>
<h5>
<small>Owner: </small>Some Dude</h5>
<br>
<p>
Enter Description for XYZProcess Server Procedure
</p>
<br>
<p>
<a href="javascript:void(0);" class="btn btn-small btnMoveDown" data-procedureid="122" data-sortorder="1"><span class="iconfa-double-angle-down">
</span>Move Down</a>
</p>
</div>
</li>
<br style="clear: both;">
<li class="span6">
<img src="../../Images/thumbs/doc.png" alt="" class="pull-left">
<div class="comment-info">
<h4>
<a href="/MasterList/ViewProcedure/122">
XYZ2 Process Server</a></h4>
<h5>
<small>Owner: </small>Some Dude</h5>
<br>
<p>
Enter Description for XYZ2 Process Server Procedure
</p>
<br>
<p>
<a href="javascript:void(0);" class="btn btn-small btnMoveUp" data-procedureid="123" data-sortorder="2"><span class="iconfa-double-angle-up icon-white">
</span>Move Up</a>
<a href="javascript:void(0);" class="btn btn-small btnMoveDown" data-procedureid="123" data-sortorder="2"><span class="iconfa-double-angle-down">
</span>Move Down</a>
</p>
</div>
</li>
<br style="clear: both;">
<li class="span6">
<img src="../../Images/thumbs/doc.png" alt="" class="pull-left">
<div class="comment-info">
<h4>
<a href="/MasterList/ViewProcedure/121">
XYZ3 Process Server</a></h4>
<h5>
<small>Owner: </small>Some Dude</h5>
<br>
<p>
Enter Description for XYZ3 Process Server Procedure
</p>
<br>
<p>
<a href="javascript:void(0);" class="btn btn-small btnMoveUp" data-procedureid="124" data-sortorder="3"><span class="iconfa-double-angle-up icon-white">
</span>Move Up</a>
<a href="javascript:void(0);" class="btn btn-small btnMoveDown" data-procedureid="124" data-sortorder="3"><span class="iconfa-double-angle-down">
</span>Move Down</a>
</p>
</div>
</li>
<br style="clear: both;">
<li class="span6">
<img src="../../Images/thumbs/doc.png" alt="" class="pull-left">
<div class="comment-info">
<h4>
<a href="/MasterList/ViewProcedure/120">
XYZ4 Process Server</a></h4>
<h5>
<small>Owner: </small>Some Dude</h5>
<br>
<p>
Enter Description for XYZ4 Process Server Procedure
</p>
<br>
<p>
<a href="javascript:void(0);" class="btn btn-small btnMoveUp" data-procedureid="125" data-sortorder="4"><span class="iconfa-double-angle-up icon-white">
</span>Move Up</a>
</p>
</div>
</li>
<br style="clear: both;">
</ul>
I'm actually (literally) writing code like this right now. I am using jQuery UI to do the drag/drop re-ordering. (This code may be a little different then most other code examples).
jQuery/javascript
$(document).ready(function ()
{
$(".ui-sortable-container").sortable({
handle: ".handle",
stop: function (event, ui)
{
AJAX.postRouteUpdate();
}
});
var AJAX =
{
postRouteUpdate: function ()
{
// create object that matches MVC object
// not case sensitive
var request = {};
request.routeIDs = [];
var selector = ".ui-routes .ui-route";
// for each of my objects grab the routeid
// this is the new order of the routeids
// send them all in, it's just easier on the backend
// and allows for future multiple re-sorts before
// sending the request to the server
$(selector).each(function (index)
{
request.routeIDs.push($(this).data('routeid'));
// update the title value, as I have mine numbered
$(this).find('.title').text((index + 1).toString());
});
$.ajax({
url: '/Routes/UpdateSequence',
data: JSON.stringify(request),
type: 'GET',
success: function (result) {
$("#procedures").html(result);
}
});
}};
Model:
public class RouteUpdateModel()
{
public IEnumerable<int> RouteIDs { get; set; }
}
Controllers
public ActionResult UpdateSequence(RouteUpdateModel model)
{
this.db().UpdateSequence(model.RouteIDs);
return this.Partial(model);
}
View
#Model RouteUpdateModel
#foreach (var routeID in model.RouteIDs)
{
//do whatever
}
I have a website in Asp.Net that I am trying to port to MVC 3 and I have only worked with MVC 2 before. I stumbled across the following asp function
<div class="popup-holder">
<ul class="popups">
<asp:Repeater runat="server" ID="ourTeamRepeater" OnItemDataBound="ourTeamRepeater_ItemDataBound">
<ItemTemplate>
<asp:Panel ID="pnlTeamMember" runat="server">
<li id="TeamMember" runat="server" class="memberImage">
<asp:Image runat="server" ID="memberImg" />
</li>
<div class="popup">
<div class="img-holder">
<asp:Image runat="server" ID="memberImgBig" />
</div>
<div class="popup-text-t">
<div class="close">
close
</div>
</div>
<div class="popup-text">
</div>
<div class="popup-text-b">
</div>
<div class="holder">
<asp:Literal ID="memberDescription" runat="server" />
</div>
</div>
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
</ul>
it looks like maybe this works similarly to a for loop, but I'm not quite positive how to convert it to MVC 3 architecture.
Porting an existing WebForms application to ASP.NET MVC is not only about blindly translating line by line some WebForms view code that you have. You should take into account the semantics of the target platform. For example converting this asp:Repeater into an ugly foreach loop instead of taking into account things like view models, display templates would not be very good.
So in ASP.NET MVC you start by designing view models:
public class MemberViewModel
{
public int Id { get; set; }
public string Description { get; set; }
}
then you design a controller action which populates this view model:
public ActionResult Index()
{
IEnumerable<MemberViewModel> model = ...
return View(model);
}
then you write a strongly typed view in which you invoke a display template:
#model IEnumerable<MemberViewModel>
#Html.DisplayForModel()
and then you define a display template which will be rendered for each element of the collection (~/Views/Shared/DisplayTemplates/MemberViewModel.cshtml):
#model MemberViewModel
<li id="TeamMember" class="memberImage">
<img src="Url.Action("ThumbnailImage", new { id = Model.Id })" alt=""/>
</li>
<div class="popup">
<div class="img-holder">
<img src="Url.Action("FullImage", new { id = Model.Id })" alt=""/>
</div>
<div class="popup-text-t">
<div class="close">
close
</div>
</div>
<div class="popup-text"></div>
<div class="popup-text-b"></div>
<div class="holder">
#Html.DisplayFor(x => x.Description)
</div>
</div>
Now you will notice the two additional ThumbnailImage and FullImage controller actions that will allows us to fetch the images of the members given the member id. For example:
public ActionResult ThumbnailImage(int id)
{
byte[] thumbnail = ...
return File(thumbnail, "image/jpeg");
}
Now that's more like ASP.NET MVC. As you can see it's a totally different pattern than classic WebForms.
You're quite right to suppose that the MVC equivalent of an asp:Repeater is
<% foreach( var item in Model )
{ %>
<!-- Your HTML Markup -->
<% } %>
You're right about it being similar to a for loop. A simple implementation might look like this:
<div class="popup-holder">
<ul class="popups">
<%foreach(var item in Model.Items) { %>
<div id="pnlTeamMember">
<img src="<%: item.MemberImageSrc %>" ID="memberImg" />
<div class="popup">
<div class="img-holder">
<img src="<%: item.MemberImgBigSrc %>" ID="memberImgBig" />
</div>
<div class="popup-text-t">
<div class="close">
close
</div>
</div>
<div class="popup-text">
</div>
<div class="popup-text-b">
</div>
<div class="holder">
<%: item.MemberDescription %>
</div>
</div>
</div>
<% } %>
</ul>
You'll notice that there are no longer any controls with runat="server", nor are there any events linked to handlers in the code-behind. Instead, we are assuming that the controller has populated the Model object with objects representing the data that we need to display. That is the role of the controller when using MVC.
A repeater is just a loop that provides databinding so that you can access the items in the collection that you are looping. If you look in the ourTeamRepeater_ItemDataBound method you will find the code that uses the databound items to populate the elements in the item template with data.
Usually you can just use a foreach loop in MVC to loop the items. Example:
<% foreach (var item in items) { %>
<div class="holder">
<%= item.Description %>
</div>
<% } %>