.NET and SQL: Do I need to build a custom control? - html

I'm working off of the default Web Forms template in VS 2013, and one of the rows has 3 divs:
<div class="col-md-4">
<h2>Get Paid</h2>
<img src="Images/adp_logo.gif" class="img-responsive" alt="ADP" />
<p>
Everybody wants to get paid! Just click on the "ADP" link to monitor or change your timesheet, benefits
information, 401K contributions, etc...
</p>
<p>
<a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301948">Go! »</a>
</p>
</div>
<div class="col-md-4">
<h2>Get Help</h2>
<asp:ImageButton ID="imgBtn2" runat="server" ImageUrl="~/Images/user_help.png" Height="100" />
<p>
Don't know how to do something? We can help! Click the image above to find answers about how to get a badge,
share your Outlook calendar, or make a great cup of coffee (okay, maybe not the last one, but you get the idea...)
</p>
<p>
<a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301949">Go! »</a>
</p>
</div>
<div class="col-md-4">
<h2>Find the People You Need</h2>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/find_icon.png" Height="100" />
<p>
You can easily find information about anybody that works at ERC. Just click and go!
</p>
<p>
<a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301950">Go! »</a>
</p>
</div>
I'd like to be able to populate these divs with information from a database row. For example, in my database I'd have a table that had Title, Image, Description, Link and Category columns. If a row had a Category of "Featured", it would populate the first element with it's Title value, the tag with the image, etc.
Do I need to build a custom control to accomplish this, or am I just overlooking an obvious way of achieving this?
By the way, the Google Play store is what I'm modeling this after, if that helps...
Thanks...

Like David said, a .NET Repeater control would be ideal for what you want to achieve. You would add your html template once and it would, well, repeat it according to your database query and the number of entries that it would extract.
Html. Note that single quotes ARE REQUIRED when binding data to an attribute like 'src', 'href', etc:
<asp:Repeater ID="myRepeater" runat="server">
<ItemTemplate>
<div class="col-md-4">
<h2><%# Eval("Title") %></h2>
<img src='<%# Eval("Image") %>' class="img-responsive" alt="ADP" />
<p>
<%# Eval("Description") %>
</p>
<p>
<a class="btn btn-default" href='<%# Eval("Link") %>'>Go! »</a>
</p>
</div>
</ItemTemplate>
</asp:Repeater>
Code-behind C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
bindRepeater();
}
}
protected void bindRepeater() {
DatabaseEntities db = new DatabaseEntities();
var query = (from q in db.myTableName
where q.Category == "Featured"
select q);
if (query.Count() > 0)
{
myRepeater.DataSource = query.ToArray();
myRepeater.DataBind();
}
}

Related

how to change text of nested html element using asp.net

I'm new to web techs. I have a bunch of elements nested in each other. I want to change some of them's texts using asp.net neither jquery nor javascript. Firstly, I need to select that element by code. Then I need to assign new text value to it.
Here's my HTML.
<div class="container">
<article class="card">
<img runat="server" id="foodImage" src="/pics/food/dolma.jpg" alt="Sample Photo" />
<div class="mealInfo">
<span class="left"><a id="foodAnchor" runat="server" href="#">Dolma Yemeği</a><br />
<span class="prepInfo">For 6-8 people Prep time 2 hours</span>
</span>
<span class="right"><i class="fas fa-clipboard"></i>
<br />
385</span>
</div>
<div class="cookInfo">
<a class="cookName" href="#"><img src="/pics/ppic.jpg"/>electricianSmurf</a>
<a class="comment" href="#"><i class="far fa-comment"></i>5</a>
</div>
</article>
</div>
Here's my ASP code. I want to dynamically change foodImage's image and foodAnchor's text. I can get those elements using their IDs but there are 8 more "card" articles(they're used as flexbox). I want to reach all of them with code and change them according to the data coming from the database(ignore this database part, firstly I need to bring elements with code)
This is a coined code represents what I want to do. Please help.
List<anchorText's type or anchor type> anchorList = new List<anchorText's type or anchor type>;
for (int i = 0; i < anchorList.Count; i++)
{
Control targetElement = FindControl("card #foodImage mealInfo left a");
if (targetElement != null)
{
anchorList.Add(targetElement);
}
}
for (int i = 0; i < anchorList.Count; i++)
{
anchorList[i].Text = textComingFromDatabase;
}

Use a specific part of code (img src) that I generated using a foreach loop in the page I open using asp-route-id and asp-page

This is probably really simple and I'm looking in completely the worng place when looking for answers online, so apologies for the noobyness of the question. Here goes...
I am developing a ASP.NET Core Web Application (using Razor Pages) and utilising Entity Framework Core in Visual Studio 2019. I have created a page that generates a bunch of different images and buttons in an OWL2 carousel using foreach based on my model:
<div class="owl_#bandModel.BandId owl-carousel owl-theme owl-drag">
#foreach (var jobTitleModel in bandModel.JobTitles)
{
#if (jobTitleModel.ImageType.ImageTypeOption != null)
{
switch (jobTitleModel.ImageType.ImageTypeOption)
{
case "Apron":
<div class="item">
#{int randomImg = random.Next(1, Apron);}
<img src="~/content/images/map/#jobTitleModel.ImageType.ImageTypeOption/img#(randomImg).svg" type="image/svg+xml" />
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="#jobTitleModel.JobTitleId" class="btn btn-outline-primary mb-2 mt-1 btn-block">#jobTitleModel.JobTitle</a>
</div>
break;
case "Casual":
<div class="item">
#{randomImg = random.Next(1, Casual);}
<img src="~/content/images/map/#jobTitleModel.ImageType.ImageTypeOption/img#(randomImg).svg" type="image/svg+xml" />
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="#jobTitleModel.JobTitleId" class="btn btn-outline-primary mb-2 mt-1 btn-block">#jobTitleModel.JobTitle</a>
</div>
break;
etc...
This is all working fine. However, when the user clicks on the button i.e.
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="#jobTitleModel.JobTitleId" class="btn btn-outline-primary mb-2 mt-1 btn-block">#jobTitleModel.JobTitle</a>
I would like to be able to take the exact image that was randomly generated and use that on the page that opens.
it would look something like this:
<img src="~/content/images/map/Apron/img5.svg" type="image/svg+xml" />
So my question is, can this be done? I've explored the asp-all-route-data helper, but I can figure it out. I want it to work in the same way that the asp-route-ID helper does, but I think that this would be wrong because it will add it to the URL.
It's worth pointing out that there isn't any database association with the images, I am having to add them in randomly from the wwwroot/contents folder (using the img#) as a random number, to esure they don't look that same every time.
Thnaks in advance.
(Thanks for the explaination and the confidence boost Fei Han, sometimes it just helps having someone say that you can do something the way you thought)
EDIT TO SHOW HOW I IMPLEMENTED #FeiHan's SUGGESTION:
Fei Han suggested that I use:
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="#jobTitleModel.JobTitleId" asp-route-ImgId="#randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block">#jobTitleModel.JobTitle</a>
The main point being the addition of the asp-route-ImgId="#randomImg" helper, however, this wasn't all I needed, as I needed to pass the ImageType into the img src as well. So I followed the logic and also included an asp-helper-tag for that too i.e. asp-route-ImgType="#jobTitleModel.ImageType.ImageTypeOption".
So my link structure looked like this:
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="#jobTitleModel.JobTitleId" asp-route-ImgType="#jobTitleModel.ImageType.ImageTypeOption" asp-route-ImgId="#randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block">#jobTitleModel.JobTitle</a>
Then I moved over to the Requirements/Index Page as reference in the link and edited the Index.cshtml.cs to include:
namespace ProjectName.Pages.UIMain.Requirments
{
public class IndexModel : PageModel
{
public string RndmImgSrc { get; set; }
public async Task OnGetAsync(int? id, int? ImgId, string ImgType)
{
RndmImgSrc = string.Format("/content/images/map/{0}/img{1}.svg", ImgType, ImgId);
//If you are a proper noob like me, a little heads-up here. You need to remove the "~" symbol from the begining of the URL (~/content/) as the Routing will add the current page route and wont refer to the wwwroot.
}
}
}
Then in the Index.cshtml I added:
#page "{ImgType?}/{ImgID?}/{ID?}" //This was just to tidy up the URL
#model ProjectName.Pages.UIMain.Requirments.IndexModel
<img src="#Model.RndmImgSrc" type="image/svg+xml" width="300"/>
And hey presto!!! it worked.
I want it to work in the same way that the asp-route-ID helper does, but I think that this would be wrong because it will add it to the URL.
You are using tag to navigate to another page, passing data through URL is ok. You can pass generated Img Id randomImg, like below.
<div class="item">
#{int randomImg = random.Next(1, Apron);}
<img src="~/content/images/map/#jobTitleModel.ImageType.ImageTypeOption/img#(randomImg).svg" type="image/svg+xml" />
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="#jobTitleModel.JobTitleId" asp-route-ImgId="#randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block">#jobTitleModel.JobTitle</a>
</div>
Besides, if you don't want to pass data randomImg as query string or route parameter in URL, you can post generated Id of img via a hidden form, like below.
switch (jobTitleModel.ImageType.ImageTypeOption)
{
case "Apron":
<div class="item">
#{int randomImg = random.Next(1, Apron);}
<img src="~/content/images/map/#jobTitleModel.ImageType.ImageTypeOption/img#(randomImg).svg" type="image/svg+xml" />
<form method="post" asp-page="/UIMain/Requirements/Index" asp-page-handler="ShowImg" asp-route-ID="#jobTitleModel.JobTitleId">
<input type="hidden" name="ImgId" value="#randomImg" />
<input type="submit" class="btnhidden" />
</form>
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="#jobTitleModel.JobTitleId" asp-route-ImgId="#randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block" onclick="return myfunc(this)">#jobTitleModel.JobTitle</a>
</div>
break;
case "Casual":
<div class="item">
#{randomImg = random.Next(1, Casual);}
<img src="~/content/images/map/#jobTitleModel.ImageType.ImageTypeOption/img#(randomImg).svg" type="image/svg+xml" />
<form method="post" asp-page="/UIMain/Requirements/Index" asp-page-handler="ShowImg" asp-route-ID="#jobTitleModel.JobTitleId">
<input type="hidden" name="ImgId" value="#randomImg" />
<input type="submit" class="btnhidden" />
</form>
<a asp-page="/UIMain/Requirements/Index" asp-route-ID="#jobTitleModel.JobTitleId" asp-route-ImgId="#randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block" onclick="return myfunc(this)">#jobTitleModel.JobTitle</a>
</div>
break;
}
Handler method ShowImg
public IActionResult OnPostShowImg()
{
//code logic here
return Page();
}
Trigger form submission while clicking <a> tag
function myfunc(el) {
$(el).prev().find("input[type='submit']").click();
return false;
}

Why erased code (OnClick event) is still running?

This little html code (my first html) ask an integer between 1 and 20 and makes a multiplication table. The multiTable is put in an aspx.cs file together. I got a plus task to change mainheader color using javascriptcode (written in script area) by OnCLientClick event. To try whether the coloring javascript function works I temporary deleted OnCLick event connected to Page_Load event. As you can see in the code asp:Button (ID=ButtonCreateMultiplicationTable) hasn't got OnClick event. But it is still functioning. Examin the input and if it is correct makes the table. How it is possible? The Code is not exist. I used: Rebuild Solution, Clean Solution, Restarted VisualStudio, Disabled cache in Chrome Developer Tools. Thank you for any help.
<div id="Date" class="dateTime"><%= (DateTime.Now.Date).ToString("yyyy/MM/dd") + " " + HungarianWeekName((DateTime.Now.DayOfWeek).ToString()).ToString() %> </div>
<div id="mainheader" class="header">
<p class="header1">Szorzótábla </p>
</div>
<div id="InputContainer" class="inputcontainer">
&nbsp
<div id="InputText2" class="inputitem1">Adjon meg egy számot 0 és 21 között </div>
&nbsp
<asp:TextBox class="inputitem2" runat="server" ID="TextBox1"></asp:TextBox>
&nbsp
<asp:Button class="inputitem3" runat="server" Text="Készít" OnClientClick="return ChangeColor()" ID="ButtonCreateMultiplicationTable" />
&nbsp
</div>
<div class="multiplicationtable" id="multitablediv">
<div class="multiplicationcontainer">
<asp:Literal ID="DynamicTable" runat="server"></asp:Literal>
</div>
</div>
An asp:button will always perform a PostBack, whether or not there is an OnClick event.
You either need to return false from the ChangeColor function.
function ChangeColor() {
//rest of your js code
return false;
}
Or don't use an asp:button
<button class="inputitem3" type="button" onclick="ChangeColor()" id="ButtonCreateMultiplicationTable">
Készít
</button>

Why does only one image from the two render?

With the following markup, I always get the same look as when for an image that isn't found: its alt and title still there but no pic.
<div class="def-orange">
<h3>Sign Up</h3>
<p>
Which kind of profile would you like?
</p>
</div>
<a href="#Url.Action("RegisterSenior", "Account", new RouteValueDictionary {{"userSide", "contractor" }})">
<img src="images/signup-contractor.png" alt="mans's head sillouheted with safety helmet" title="As a Senior">
</a>
<a href="#Url.Action("RegisterEmployer", "Account", new RouteValueDictionary {{"userSide", "employer" }})">
<img src="/Images/signup-employer.png" alt="mans's head sillouheted with collar and tie" title="As an Employer">
</a>
<div class="def-orange">
Already have an account? #Html.ActionLink("Sign In", "Login", "Account")
</div>
I know both images are present because I can swap them around, and both images display when they are on the right hand one of the two a tags, and neither displays when they are in the left hand a tag.
Change images/signup-contractor.png to /Images/signup-contractor.png

If statement in HTML

Hello i have list of products this my html
<telerik:RadListBox ID="RadListBox1" runat="server" DataSourceID="LinqDataSourceCategories" Height="200px" Width="250px" CssClass="ui-droppable" >
<EmptyMessageTemplate>
No records to display.
</EmptyMessageTemplate>
<ItemTemplate >
<div class="ui-draggable ui-state-default" data-shortid="<%#Eval("ID")%>">
<em>Active : </em><span><%# Eval("LoadProduct") %></span><br />
<em>ProductId: </em><span><%# Eval("ProductId") %></span><br />
</div>
</ItemTemplate>
</telerik:RadListBox>
I have Active that is say if LoadProduct true or false
in client it look like this
<em>Acrive : </em>
<span>False</span>
<br>
<em>ProductId: </em>
<span>101-01-056-02</span>
<br>
<em>ShortID: </em>
<span class="ShortID" data-shortid="0">0</span>
<br>
I want to replace text with img ,i need to check if <%# Eval("LoadProduct") %> ==true put img scr=/green.png/ else img scr=/red.png/ that clien will look like this
<em>Acrive : </em>
<span><img src='green.jpg'/></span>
<br>
<em>ProductId: </em>
<span>101-01-056-02</span>
<br>
<em>ShortID: </em>
<span class="ShortID" data-shortid="0">0</span>
<br>
Sow how it can be done?
To add if statement to HTML,
or to catch event that building all elements and there check if LoadProduct==true and append html to item?
try this
<em>Active : </em><span><%# Convert.ToBoolean(Eval("LoadProduct")) ? "<img src='green.jpg'/>" : "<img src='red.jpg'/>"%></span><br />
Come to think of it, I don't really like the idea of back-end conditionals in front-end.
Code-behind is one thing and frontside is the other - it's not a good idea to mix it if it isn't inevitable.
The purest way to get that would be to set the variable (or a function, in your case) in code-behind and just to show it in front-end, like:
Code behind:
protected string GreenOrRed(bool isLoadProduct)
{
return isLoadProduct ? "green" : "red";
}
(the function or variable has to be at least protected in order to be accessible in aspx page, because the aspx page is the derivative from base class of aspx.cs )
front-end:
<span><img src='<%# GreenOrRed((bool)Eval("LoadProduct")) %>.jpg'/></span>
After that, remeber to add
this.DataBind();
in your Page_Load() function.
Let the code-behind decide, let the front-end only show the result.
<%
if((bool)Eval("LoadProduct") == true)
{
Response.Write("src='green.jpg'");
}
else Response.Write("src='red.jpg'");
%>
Try this
<img src='<%# (bool)Eval("LoadProduct") ? "green.jpg" : "red.jpg" %>'/>