How to use if statement into foreach in razor? - html

I try to use two if statement into foreach such as this but in second if statement get error.Please advice
#{
string path = System.Configuration.ConfigurationManager.AppSettings["ImageEdit"];
int i = 0;
}
#foreach (var item in Model.PhotoTables)
{
if (i < 1)
{ <div class="row">
}
<div class="col-xs-2 col-wrapper">
<div class="image-wrapper">
<img src="#Url.Content(path+item.PhotoName)" alt="" />
<img class="delimg" src="~/Content/Adminex/images/delete-icons.png" id="#item.Id" />
</div>
</div>
#if (i < 1 )
{
</div>}
</div>
i++;
}

You seem to have an extra closing div with no matching start tag.
Your code block can contain all of the logic. Try:
#{
string path = System.Configuration.ConfigurationManager.AppSettings["ImageEdit"];
int i = 0;
foreach ( var item in Model.PhotoTables )
{
if ( i < 1 )
{
<div class="row">
}
<div class="col-xs-2 col-wrapper">
<div class="image-wrapper">
<img src="#Url.Content(path + item.Name)" alt="" />
<img class="delimg" src="~/Content/Adminex/images/delete-icons.png" id="#item.Id" />
</div>
</div>
#if (i < 1 )
{
</div>
}
i++;
}
}
You only need the # symbol on the containing codeblock.
The # symbol is not required when you directly nest actual code blocks (not HTML), so the first foreach, and if are ok, but then we go into HTML, and then back to code for the second if - we need to use a #.

Manually manipulating a variable inside a foreach statement can possibly lead to trouble. Instead, take advantage of current framework method Select().
Model:
var model = new SampleViewModel
{
Items = new List<string>
{
"A",
"B",
"C"
}
};
return View(model);
}
Razor:
#foreach(var item in Model.Items
.Select((value, index) => new { Value = value, Index = index }))
{
if ( item.Index < 1 )
{
<div class="row">
}
<div>#item.Index #item.Value</div>
if ( item.Index < 1 )
{
</div>
}
}
Results:
0 A
1 B
2 C
DotNetFiddle MVC Example

Related

Delete row from DIV table when button clicked

I have the following divTable:
<div class="divTable">
<div class="divTableBody">
<div class="divTableRow">
<div class="divTableCell">TagName</div>
<div class="divTableCell">Higher/Lower</div>
<div class="divTableCell">Threshold</div>
<div class="divTableCell">Delete Alert?</div>
</div>
<div class="divTableRow" *ngFor="let com of currentAlerts">
<div class="divTableCell">{{com.tagname}}</div>
<div class="divTableCell">{{com.symbol == 1 ? 'Higher than' : 'Lower than'}}</div>
<div class="divTableCell">{{com.threshold}}</div>
<div class="divTableCell">
<button mat-stroked-button color="primary" (click)="submit(com.ID)">
Delete
</button>
</div>
</div>
</div>
As you can see this table loops through the array currentAlerts and creates a row for each item found.
The array is popuplated within ngOnInit() by connecting to a web API.
this.alerts.getCurrentAlerts(this.loginEmail)
.subscribe
((data: CurrentAlerts[]) => {this.currentAlerts = data;
console.log(this.currentAlerts.length)
if(!this.currentAlerts || !this.currentAlerts.length){
this.alertsTitleMessage = "You have no alerts configured."
}else{
this.alertsTitleMessage = "Here are the Alerts you have set up "
}}
);
When the Delete button is clicked the a delete request is sent to the database.
submit(ID){
let isDeleted = null;
this.alerts.deleteCurrentAlert(ID).subscribe(result => isDeleted = result);
this.manageCurrentAlerts();
}
All the above works as expected and the data is deleted from the database.
Question
How do I get the table to remove the deleted row? I have read answers that state to delete the row from the arra using splice but I couldnt get that working.
Add index in ngFor, *ngFor="let com of currentAlerts;let i = index"
In delete button, pass index i.e i instead of com.ID
Use splice in TS function, this.currentAlerts.splice(index,1)
Try like this:
<div class="divTableRow" *ngFor="let com of currentAlerts;let i = index">
...
<div class="divTableCell">
<button mat-stroked-button color="primary" (click)="submit(i)">Delete</button>
</div>
</div>
TS
submit(index){
this.currentAlerts.splice(index,1)
...
}
After deletion from database delete it from array.
submit(ID){
let isDeleted = null;
this.alerts.deleteCurrentAlert(ID).subscribe(result => isDeleted = result);
this.manageCurrentAlerts();
for(var i = 0; i< this.currentAlerts.length ; i++) {
if(this.currentAlerts[i].ID === ID) {
this.currentAlerts.splice(i, 1);
}
}
}
In your response from the server you need to delete the item from the array so in your method:
this.alerts.deleteCurrentAlert(ID).subscribe(result => isDeleted = result);
you should apply the filter method. Splice could work too but Filter has better performance.
Your method should look like this :
this.alerts.deleteCurrentAlert(ID).subscribe(result => {
this.currentAlerts = this.currentAlerts.filter(item => item.ID != ID);
isDeleted = result;
});

Retrieving Image from folder using codeigniter

I want to retrieve image from folder and rest of data from database using CodeIgniter.
Right now I am able to retrieve data only from database.
Can anyone explain how to get an image from any folder and display it in a web page.
Follow this procedure:
Model
function getDataByID ($user_id)
{
$q = $this->db->query("SELECT name, image FROM tbl_user WHERE user_id = $user_id");
if ($q->num_rows() > 0) {
$d = $q->row_array();
if ($d['image'] != '') {
$temp = $d['image'];
$d['image'] = "http://domain.com/myimages/".$temp;
} else {
$d['image'] = '';
}
return $d;
} else {
return array();
}
}
Controller
function user_detail($user_id)
{
$dt = $this->code_model->getDataByID($user_id);
$display['user_data'] = $dt;
$this->load->view('user_view',$display);
}
View
if(isset($user_data) && !empty($user_data)) {
extract($user_data);
} ?>
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-6">
<?php echo $name; ?>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Image</label>
<div class="col-lg-6">
<img src="<?=$image?>">
</div>
</div>
I am not sure how you are constructing the page, but the easiest way to add an image is to set the data to a variable in PHP and adding it to the <img> tag:
<img src="{base_url}_assets/_images/folder/<?=$productData[0]->Image1?>" />

Align loop output in one row

I have this code in which the image output $check or $uncheck and title $val_c are inside a loop, what i want is to output everything in one row using <div class="col-sm-12"> but what i always get is a column. what i want is like this
image_title_______________image_title________________image_title
what im getting is like this...
image
title
image
title
image
title
heres is the code
<div class="panel-body">
<div class="col-sm-12">
';
$funcs->viewSurvey();
$array4 = $funcs->viewSurvey();
$searchengine = $array4['searchengine'];
$sum = $array4['sum'];
$searches = explode(',', $searchengine);
$searchesa = array("google","yahoo","bing");
$check = '<img src="images/checked.png" height="40px" width="40px">';
$uncheck = '<img src="images/unchecked.png" height="40px" width="40px">';
foreach ($searchesa as $key_a => $val_c) {
$found = false;
foreach ($searches as $key_b => $val_d) {
if ($val_c == $val_d) {
echo ''.$check.'<h3 class="head8">'. $val_c.'</h3>' ;
$found = true;
}
}
if (!$found)
echo ''.$uncheck.'<h3 class="head8">'. $val_c.'</h3>' ;
}
echo '
</div>
</div>
Use this style
h3 {
display:inline;
}
I already solved it. i just placed the <div class="col-sm-12"> inside the first foreach.

Problems with getting an image to show in a paged list

I have the following code, and it displays the listed text and the pagination at the bottom all fine. But when I try to get the images from the child page into the list it errors for me. Any ideas why?
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#{
Layout = "SiteLayout.cshtml";
}
<div role="main" id="main">
<div id="blogPageFeatures">
<!-- loop through all of the child pages (blog posts) and grab data to output as a summary -->
#{
var pageSize =3;
var page =1;int.TryParse(Request.QueryString["page"],out page);
var items =Model.Content.Children().Where(x => x.IsDocumentType("BlogArticle")).OrderByDescending(x => x.CreateDate);
var totalPages =(int)Math.Ceiling((double)items.Count()/(double)pageSize);
if(page > totalPages)
{
page = totalPages;
}
else if(page <1)
{
page =1;
}
}
#foreach(var item in items.Skip((page -1)* pageSize).Take(pageSize))
{
<a href="#item.Url">
<!-- The next image line is where it errors -->
<img src="#Umbraco.Media(item.Children.blogArticleImage).Url">
<h2>#item.Name</h2>
<p class="blogTileDate">#item.CreateDate.ToString("dd/MM/yy")</p>
</a>
}
<div class="clearfix"></div>
<!-- Pagination START -->
#if(totalPages >1)
{
<div class="pagination">
<ul>
#if(page >1)
{
<li>Prev</li>
}
#for(int p =1; p < totalPages +1; p++)
{
var active =(p == page)?" class=\"active\"":string.Empty;
<li#(Html.Raw(active))>
#p
</li>
}
#if(page <totalPages)
{
<li>Next</li>
}
</ul>
</div>
}
<!-- Pagination END -->
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
You are getting Model.Content.Children, which is a strongly typed collection of IPublishedContent objects. You are then calling item.Children.blogArticlImage, which is not going to work, as you're trying to get the a property on the children of the item, not a property of the item itself. You're also trying to use dynamic syntax, which won't work on the strongly typed objects. Try changing your image code to:
<img src="#Umbraco.TypedMedia(item.GetPropertyValue<int>("blogArticleImage")).Url">
That should do te trick, one thing to note is that if an item doesn't have an image set, or the image that has been selected has been deleted, it'll throw an error. A more robust approach would be something like this:
var imageSrc = "ADD DEFAULT IMAGE PATH HERE";
var media = Umbraco.TypedMedia(item.GetPropertyValue<int>("blogArticleImage"));
if (media != null && !string.IsNullOrEmpty(media.Url))
{
imageSrc = media.Url;
}
<mig src="#imageSrc">

insert dynamic 6 images into 2 lines via bootstrap

i try without luck to insert 6 images into 2 lines,
the problem is that the line number 2 break the last 2 images and push them down.
i'm using Umbraco and bootstrap 3.
here is my code
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#{
Layout = "InnerPage.cshtml";
}
#section slider
{
#{Html.RenderPartial("ImageSlider");}
}
#{
<!-- PROGRAM PAGE -->
<script src="js/script.js"></script>
<div class="caption-button caption-gray left-top" style="font-size:14px;">UPCOMING EVENTS</div>
<div class="padding-top-60">
<div class="row row-lg-height">
<div id="eventCarousel" class="carousel slide vertical" >
<div class="carousel-inner">
#{
var content = Umbraco.Content(1122);
int itemsCount = content.Children.Count();
int sliders = itemsCount / 6;
for (int i = 0; i <= sliders; i++)
{
var items = content.Children;
if (i == 0)
{
#Html.Raw("<div class=\"item active\">")
items = content.Children.Take(6);
}
else
{
items = content.Children.Skip(i * 6).Take(6);
#Html.Raw("<div class=\"item\">")
}
foreach (var childContent in items)
{
var contentService = ApplicationContext.Current.Services.ContentService.GetById(int.Parse(childContent.Id.ToString()));
var title = childContent.Name.ToString();
var image = Umbraco.Media(contentService.Properties["Thumbnail"].Value.ToString());
var description = contentService.Properties["shortDescription"].Value.ToString();
var img = image.Url.ToString();
<div class="col-lg-4">
<img src="#image.Url" class="media-object pull-left img-responsive" />
<h1 class="media-heading" style="color:#606060;">#title</h1>
<div style="padding:0px 5px; ">#MvcHtmlString.Create(#description)</div>
</div>
}
#Html.Raw("</div>")
}
}
</div>
</div>
</div>
</div>
<a class="caption-button caption-red right-bottom" href="#eventCarousel" data-slide="next">MORE</a>
}
i attached 2 images so you can see what firebug showing to me and what happened on the screen.
PLEASE HELP ME ! I am breaking my head 2 days already and it's wasting my time..
What do i do wrong ??
I think your code is a littlebit difficult. If you use another approach you will be able to debug much easier.
Try some approach like this:
#{
var allNodesToLoop = Umbraco.Content(1122).Children;
}
#foreach(var nodegroup in allNodesToLoop.InGroupsOf(2) {
<div class="row">
#foreach(var item in nodegroup) {
<div class="col-md-4">
#item.Name
<!-- and other stuff you want to render in this grid cell -->
</div>
}
</div>
}