ASP.net Image to ListView From Data - c#

Morning guys, Using MS Visual Studio 2012, ASP.net/C# 3.5.(not MVC)
I have a list view that is bound in code behind from my model.
It currently displays on screen as columns with 0, 1 or ''. i would like to replace these at runtime with images (tick or cross) and show no image if the value is ''.
Now i have the following snippet of code:
<asp:ListView ID="lvSearchUser" runat="server">
<div class="hidden">
<div id="<%#Eval("userid") %>" class="target">
<div class="emptyTitle" style="width:680px;">
<div class="videosViewed">Videos Viewed</div><div class="module13">Module13</div><div class="module12" >Module12</div>
<div class ="module11" >Module11</div><div class="module10">Module10</div><div class="totalTime">Total Time</div>
</div>
<div class="videosViewed" ><%#Eval("VideosViewed") %> </div>
<div class="module13"> <%#Eval("ModuleNum13") %> </div>
<div class="module12"> <%#Eval("ModuleNum12") %> </div>
<div class="module11"> <%#Eval("ModuleNum11") %> </div>
<div class="module10"> <%#Eval("ModuleNum10") %> </div>
<div class="totalTime"> <%#Eval("TotalTime") %> </div>
</div>
</div>
<div style="clear:both"></div>
code behind is :
private void ShowGrid()
{
//dgvUserResults.DataSource = null;
List<ModelSearchUser> dbuser = runSQL.GetUserFinal(GetSearchInput(), GetCountryInput(), GetUserTypeInput(), GetGroupInput(), GetCodeUsageInput(), GetCompletedInput());
lvSearchUser.DataSource = dbuser;
this.lvSearchUser.DataBind();
}
please note this is not a datagrid its listview that has divs wrapped inside to act like a grid.
So anyone have a solution to this? (unfortunately one that also works with IE7...shudders*)

Assuming that ModuleNum13 is and int in the datasource when binding, how about:
<div class="module13">
<asp:Image id="tick" runat="server" Visible='<%# Eval("ModuleNum13") is int && ((int)Eval("ModuleNum13")) == 1 %>' ImageUrl="/image/tick.jpg" />
<asp:Image id="cross" runat="server" Visible='<%# Eval("ModuleNum13") is int && ((int)Eval("ModuleNum13")) == 0 %>' ImageUrl="/image/cross.jpg" />
</div>
And similar for the other fields. This is not elegant but should work...

Related

Cant get text from textbox

So, I need to get a string from a textbox to use in a backend program, but I'm unable to get it when im one the site, however it works if i set Text="Test1" prior, even though i change the text in the textbox, "Test1" always gets sent to to my function and works! (Talking about Box3)
Code to the text boxes below
<div class="row">
<form action="#" method="post" class="contact-form">
<div class="col-md-4 col-sm-6">
<asp:TextBox ID="Box3" Text="Test1" runat="server" placeholder="Gamepin..."></asp:TextBox>
</div>
<div class="col-md-4 col-sm-6">
<asp:TextBox ID="Box2" runat="server" placeholder="Name ..."></asp:TextBox>
</div>
<div class="col-md-4 col-sm-12">
<asp:TextBox ID="Box1" runat="server" placeholder="Amount ..."></asp:TextBox>
</div>
<div >
<asp:CheckBox ID="CheckBoxREPLY" runat="server" style="vertical-align: central" Text="YesNo" TextAlign="Left" />
</div>
<div class="col-md-12 col-sm-12">
<input type="button" runat="server" onserverclick="Funcactivate" class="button big green" value="Launch!"/>
</div>
</form>
</div>
And my code to get textbox.text
protected void Funcactivate(object sender, EventArgs e)
{
//Get textbox(s)
string Game = Box1.Text;
string Namepref = Box2.Text;
string Amount = Box3.Text;
}
Changing your button could work.
<asp:Button ID="btnLaunch" runat="server" Text="Launch!" class="button big green" OnClick="Funcactivate" CausesValidation="False"/>
If you are using web forms, you should be able to capture the text box entry in the "if(!IsPostBack){...}" event and set it to a variable and use it in your "Funcactivate" method.
Hello Sleepwalker, here is a code sample that works for me, I am not using the isPostBack. I am also using an asp:button Instead of using an HTML input control.
<div>
<asp:TextBox ID="txtBox1" runat="server"></asp:TextBox>
</div>
<div>
<asp:TextBox ID="txtBox2" runat="server"></asp:TextBox>
</div>
<div>
<asp:TextBox ID="txtBox3" runat="server"></asp:TextBox>
</div>
<div>
<asp:Button ID="btnSubmit" runat="server" Text="Button" OnClick="btnSubmit_Click" />
</div>
protected void btnSubmit_Click(object sender, EventArgs e)
{
string game = this.txtBox1.Text.ToString();
string Namepref = this.txtBox2.Text.ToString();
string Amount = this.txtBox3.Text.ToString(); //box3;
}
I fixed it by moving my form to only get the < asp:X, because i discovered that if the < asp:x was nested too deep within a ton of divs, it didnt work properly.
It may have been due to something else, but it worked for me.

Cannot implicitly convert type 'string' to 'System.Web.UI.WebControls.TextBox' Error

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.

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();
}
}
}

mvc 3 equivalent to <asp:repeater> function?

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>
<% } %>

.net Html.RenderAction returns binary instead of HTML. Huh?

I'm not sure exactly what I'm doing wrong here.
I have an action which returns a partial view:
public class SharedController : BaseController
{
public ActionResult StudentPoll()
{
WAM.X2O.FuelUpToPlayContext db = new WAM.X2O.FuelUpToPlayContext(WAM.Utilities.Config.ConnectionString);
WAM.X2O.StudentPoll m = (from s in db.StudentPolls where s.IsActive == true select s).SingleOrDefault();
return PartialView("StudentPoll", m);
}
}
I implement the action like this:
<%Html.RenderAction("StudentPoll", "Shared");%>
The partial view looks like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl< Fuel_Up_To_Play.Models.Shared.StudentPollModel >" %>
<%if(ViewData.Model != null){ %>
<div class="block">
<div class="holder">
<div class="frame">
<h2 class="poll">Student Poll</h2>
<!-- TODO - Student Poll has a form screen, and results screen.
Results anim is here to demo what should happen after submision -->
<form action="/Shared/SubmitStudentPoll" method="post" class="poll-form" <%if(ViewData.Model.StartingState == Fuel_Up_To_Play.Models.Shared.StudentPollModel.PollStates.RESULTS){%>style="display:none"<%} %>>
<fieldset>
<span><%=ViewData.Model.StudentPoll.Question %></span>
<input type="hidden" id="student_poll" name="student_poll" value="<%=ViewData.Model.StudentPoll.ID %>" />
<%foreach(WAM.X2O.StudentPollAnswer answer in ViewData.Model.StudentPoll.RelatedStudentPollAnswers){ %>
<div class="row">
<input type="radio" class="radio" id="answer_<%=answer.ID %>" name="poll_answer" value="<%=answer.ID %>"/>
<label for="answer_<%=answer.ID %>"><%=answer.AnswerText%></label>
</div>
<%} %>
<input id="submitBtn" type="image" style="display:none" class="image" src="/Content/images/btn-submit-05.gif" />
</fieldset>
</form>
<div class="progress-box" <%if(ViewData.Model.StartingState == Fuel_Up_To_Play.Models.Shared.StudentPollModel.PollStates.FORM){%>style="display:none"<%} %>>
<span><%=ViewData.Model.StudentPoll.Question %></span>
<%int answerCounter = 0;
foreach(WAM.X2O.StudentPollAnswer answer in ViewData.Model.StudentPoll.RelatedStudentPollAnswers){ %>
<div class="box">
<span class="names"><%=answer.AnswerText%><strong class="quesPctTxt" rel="<%=ViewData.Model.AnswerPercentages[answerCounter] %>"></strong></span>
<div class="progress-bar"><span class="quesPctBar"></span></div>
</div>
<%
answerCounter++;
} %>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/Scripts/studentpollscript.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input.radio[name='poll_answer']").change(function() {
$("#submitBtn").show();
});
$("#submitBtn").click(function() {
$(".poll-form").ajaxForm(
{ dataType: 'json',
success: function(json) {
alert(json.Success);
}
}
);
});
});
</script>
<%} %>
Natually, I would expect this approach to return HTML. But no. Instead it appears that binary is being rendered in the browser. Obviously I'm doing something wrong but I don't know what.
Here's what is rendered in the browser:
http://screencast.com/t/Mjg1OWJj
Any ideas folks? I'm stumped but I'm sure it's something simple that I'm missing.
I would guess that it simply isn't setting the content type correctly. What does a network trace (fiddler, etc) show? Perhaps try using View("StudentPoll", m); instead of PartialView(...)?
Also; be careful - many of those <%= look unsafe, i.e. not html-encoded.

Categories

Resources