could not display image from database in one to many relation database - c#

i was creating a two model for upload a multiple image.for that i have used one to many relationship database for imagelist.but this image's failed to show my browser.here is my code:
model
public class test
{
public string Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public List<Photo> Photos { get; set; }
}
//another model
public class Photo
{
public string PhotoId { get; set; }
public string Image { get; set; }
}
here i upload multiple image
Controller
[HttpPost]
public IActionResult Create(test product, IFormFile[] photos)
{
test t = new test();
if (photos == null || photos.Length == 0)
{
return Content("File(s) not selected");
}
else
{
product.Photos = new List<Photo>();
foreach (IFormFile photo in photos)
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Images", photo.FileName);
var stream = new FileStream(path, FileMode.Create);
photo.CopyToAsync(stream);
//product.Photos.Add(photo.FileName);
product.Photos.Add(new Photo { Image = "Images/" + photo.FileName });
}
}
_db.test.Add(product);
_db.SaveChangesAsync();
return View();
}
this controller i used for display:
public IActionResult Index()
{
return View(_db.test.ToList());
}
here is the view of index.cshtml
<h1 class="text-center text-danger">Buy Now!!</h1>
<br /><br />
#using Practise.Models
#model List<test>
<div class="row">
#foreach (var laptop in Model)
{
<div class="col-4 ml-5">
<div class="card mb-4">
<div class="card-header">
<h4 class="my-4 font-weight-normal">
<label style="font-size:23px; color:black;text-align:center">#laptop.Name</label>
</h4>
</div>
<img src="~/#laptop.Photos" alt="Card Image" class="card-img-top" style="height:300px;" />
<div class="card-header">
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<label style="font-size:20px;color:darkblue"><b>Price:#laptop.Price</b></label>
</div>
<a asp-action="Details" asp-controller="ShopShow" asp-route-id="#laptop.Id" class="btn btn-primary pull-right btn-outline-light">Details</a>
</div>
</div>
</div>
</div>
}
</div>
when i run the application.i could not find the expection output.that means, could not display image.
enter image description here
above output,i want to show here photo. what is the solution of this?

Assuming you need to show the first image only even if multiple images are present. Rewrite your img tag like below
#if(laptop.Photos!=null && laptop.Photos.Count!=0)
{
<img src="~/#laptop.Photos[0].Image" alt="Card Image" class="card-img-top" style="height:300px;" />
}

Related

Display data from a drop down in the view asp.net core

I have a view that needs to display a drop-down and then displaying data from the drop-down in the same view using viewBag
There is 3 tables customer, assign, employee. Assign and employee have a relationship but the customer does not and is not needed so ViewBag is being used to display data in another view, how I build a drop-down list displayed in the view using the viewBag and display the selected data from the customer table in the same view?
The view that the data is needed to be displayed in mainly the name, task, and image from the URL
#model HandyApp.Models.ViewModels.AsignVM
<div>
// drop down needed in this section
</div>
<div>
// display data from selected drop down item needed in this section
</div>
<form method="post" asp-action="Create">
<div class="container">
<div class="form-row">
<div class="col-md-12">
<h1>Customer task</h1>
</div>
</div>
<div class="form-row">
<div class="col-md-12"><strong style="margin-right: 7px;">Name :</strong><span style="margin-top: 1px;">harry</span></div>
</div>
</div>
<div class="container">
<div class="form-row">
<div class="col-md-12"><strong>Tasks :</strong><span style="margin-left: 12px;">paint shed</span></div>
</div>
</div>
<div class="container">
<div class="form-row">
<div class="col-md-12"><strong>Telephone number :</strong><span style="margin-left: 12px;">000000000000</span></div>
</div>
</div>
<div class="container">
<div class="form-row">
<div class="col"><strong>Address : </strong><span>123 Fake Street</span><span></span></div>
<div class="col-md-12" style="margin-top: 31px;">
<h3 style="margin-left: 0px;">Assign tasks</h3>
</div>
</div>
<div class="form-row">
<div class="col-md-3">
<label style="margin-left: 47px;">Name of customer</label>
<input asp-for="Asign.Name" class="form-control" type="text" value="customers name" style="margin-top: 2px;">
<label style="margin-top: 8px;">Employee Assign </label>
<select asp-for="Asign.EmployeeNameId" asp-items="#Model.TypeDropDown" class="form-control">
<option selected>-- Select option</option>
</select>
<label style="margin-top: 8px;">Employee Assign </label>
<select asp-for="Asign.Status" class="form-control">
<option value="in progress" selected="">in progress</option>
<option value="completed">completed</option>
</select>
</div>
<div class="col-md-3">
<label style="margin-left: 54px;">Tasks </label>
<input asp-for="Asign.Tasks" class="form-control" value="Enter tasks here" style="margin-top: 4px;">
<label style="margin-top: 8px;">Telephone</label>
<input asp-for="Asign.Telephone" value="Type telephone" class="form-control" type="text">
<label tyle="margin-top: 8px;">Address</label>
<input asp-for="Asign.Address" class="form-control" value="enter address" type="text"></div>
</div>
<button class="btn btn-primary" type="submit" style="margin-top: 35px;margin-left: 34px;">Submit</button>
</div>
</form>
Customer model
public class Customer
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Tasks { get; set; }
public string Telephone { get; set; }
public string Address { get; set; }
public string ImageUrl { get; set; }
}
Assign model
public class Assign
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Tasks { get; set; }
public string Telephone { get; set; }
public string Address { get; set; }
public string Status { get; set; }
public string ImageUrl { get; set; }
public int EmployeeNameId { get; set; }
[ForeignKey("EmployeeNameId")]
public virtual Employee Employee { get; set; }
}
Employee model
public class Employee
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Speciality { get; set; }
}
Assign ViewModel
public class AssignVM
{
public Assign Assign { get; set; }
public IEnumerable<SelectListItem> TypeDropDown { get; set; }
}
Assign controller
public class AssignController : Controller
{
private readonly ApplicationDbContext _db;
public AssignController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
IEnumerable<Asign> objList = _db.Assigns;
IEnumerable<Customer> custObj = _db.Customers;
foreach (var obj in objList)
{
obj.Employee = _db.Employees.FirstOrDefault(u => u.Id == obj.EmployeeNameId);
}
ViewBag.Customer = custObj;
return View(objList);
}
public IActionResult Create()
{
AssignVM assignVM = new AssignVM()
{
Assign = new Assign(),
TypeDropDown = _db.Employees.Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
})
};
return View(assignVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(AssignVM obj)
{
_db.Assigns.Add(obj.Assign);
_db.SaveChanges();
return RedirectToAction("Index");
}
public IActionResult Delete(int? id)
{
if (id == null || id == 0)
{
return NotFound();
}
var obj = _db.Assigns.Find(id);
if (obj == null)
{
return NotFound();
}
return View(obj);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int? id)
{
var obj = _db.Assigns.Find(id);
if (obj == null)
{
return NotFound();
}
_db.Assigns.Remove(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
}
Use a jquery to get data from controller will be the easiest way, you can check my demo:
The image is stored in wwwroot/Images/*** in my demo.
Controller:
[HttpGet]
public JsonResult GetCustomer(string Id)
{
var img = _db.Customers.Where(x => x.Id.ToString()==Id).ToList();
return Json(img);
}
View:
<div>
<select class="form-control" id="select1" asp-items="#(new SelectList(ViewBag.customers,"Value", "Text"))">
</select>
</div>
<div id="showhere">
</div>
//........your other html
#section Scripts
{
<script>
$(document).ready(function () {
$("#select1").change(function () {
var Id = $("#select1 option:selected").val();
$.ajax({
type: 'Get',
url: 'Assign/GetCustomer',
data: { Id: Id },
dataType: "json",
success: function (data) {
document.getElementById("showhere").innerHTML = "";
document.getElementById("showhere").innerHTML +=
"<img src=" + data[0].imageUrl + " height="+50+" width="+50+">";
}
});
});
});
</script>
}
Result:

multiple image list failed to be displayed

I want to display my multiple image list which I uploaded my specific product. but when I using a loop for display, I don't understand why?.here is my code:
Model
//model for multiple images
public class Photo1
{
[Key]
public int PhotoId { get; set; }
public string Image { get; set; }
}
//main model
public class Shop
{
public int Id { get; set; }
[Required]
[Display(Name = "product name")]
public String Name { get; set; }
[Required]
public int Price { get; set; }
public String Image { get; set; }
public String Image1 { get; set; }
public List<Photo1> Photos { get; set; }
[Required]
public int Quantity { get; set; }
[Required]
public bool IsAvailable { get; set; }
[Display(Name = "Category")]
public int? CategoryTypeId { get; set; }
[ForeignKey("CategoryTypeId")]
public Category Category { get; set; }
[Display(Name = "SubCategory")]
public int? SubCategoryTypeId { get; set; }
[ForeignKey("SubCategoryTypeId")]
public SubCategory SubCategory { get; set; }
}
Controller
[HttpGet]
public ActionResult Details(int? id)
{
if (id == null)
{
return NotFound();
}
var product = _db.Shop.Include(c => c.Category).Include(c => c.SubCategory).FirstOrDefault(c => c.Id == id);
if (product == null)
{
return NotFound();
}
return View(product);
}
}
Details.cshtml
#model DigitalShop.Models.Shop
#{
ViewData["Title"] = "Details";
}
<br />
<h2 class="text-danger"> Product Details</h2>
</br></br>
#*<div class="col-8 position-relative ">
<img src="~/#Model.Image" width="425px" height="200px" sizes="cover" style="background-size:cover" />
</div>*#
<form method="post" asp-action="" enctype="multipart/form-data">
<div class="row">
<div class="col-1 ml-4">
<img src="~/#Model.Image" style="width:100%" onclick="myFunction(this);">
</br></br>
#*<img src="~/#Model.Image1" style="width:100%" onclick="myFunction(this);">*#
</br></br>
#if (Model.Photos != null)
{
#foreach (var photo in Model.Photos)
{
#if (photo != null)
{
<img src="~/#photo.Image" alt="Card Image" class="card-img-top" style="height: 120px;" onclick="myFunction(this);"/>
}
}
}
</div>
<div class="col-4 container">
<span onclick="this.parentElement.style.display='none'" class="closebtn">×</span>
<img src="~/#Model.Image" class="active" id="expandedImg" style="width:100%">
<div id="imgtext"></div>
</div>
<div class="col-4">
<h2><i class="fa fa-heart-o" aria-hidden="true"></i> #Model.Name</h2>
<input type="hidden" asp-for="Id" />
</br>
<h4>#Model.Price $</h4></br>
<small class="text-danger">Clearence</small>
<hr>
</br></br></br></br>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<div class="col-sm-12 col-xs-12 spinner-block">
<div class="number-spinner">
<div class="input-group number-spinner">
<b class="mr-4"> <label asp-for="#Model.Quantity"></label></b></br>
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number btncartsniper" data-type="minus" data-dir="dwn"><span class="fa fa-minus fa-sm"></span></button>
</span>
<input asp-for="#Model.Quantity" class="form-control input-number Snippper_qty" value="0" type="number">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-number btncartsniper" data-type="plus" data-dir="up"><span class="fa fa-plus fa-sm"></span></button>
</span>
</div>
</div>
</div>
</br>
#*#if (leathers != null)
{*#
<button type="submit" class="btn btn-danger form-control" asp-action="Remove" asp-route-id="#Model.Id">Remove To Cart</button>
#*}*#
#*else
{*#
<input type="submit" value="Add To Cart" class="btn btn-dark form-control" />
#*}*#
</div>
</div>
<div>
<a asp-action="Index" class="btn btn-danger">Back To List</a>
</div>
</form>
#section Scripts{
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
<script>
function myFunction(imgs) {
var expandImg = document.getElementById("expandedImg");
var imgText = document.getElementById("imgtext");
expandImg.src = imgs.src;
imgText.innerHTML = imgs.alt;
expandImg.parentElement.style.display = "block";
}
</script>
}
my output is :
but I want to show my all multiple photos of every product. I failed to understand what's the solution to this.
You should loop through Photos.
That's what the error indicates. It tries to find the enumerator of Shop (Model), while you're intending to loop through photos.
#if (Model.Photos != null)
{
#foreach (var photo in Model.Photos)
{
#if (photo.Image != null)
{
<img src="~/#photo.Image" alt="Card Image" class="card-img-top" style="height: 120px;"/>
}
}
}
You should also include Photos to the product you're returning, otherwise the list will be null.

How to get the View to return the ID via a ViewModel to the controller?

I currently have a view which returns an IEnumerable collection of Technicians via the TechnicianViewModel. The view model populates fine and displays the objects correctly.
However, at the moment I need someone to point me in the right direction with regards to selecting a specific technician.
If I was to click More Info on the technician, an [HttpGet] request would be initiated which would result in a queryString. And this is exactly what is against the requirements of this project.(Requirements of the project: no query string should appear in the URL)
Here is the view :-
#model IEnumerable<ActionAugerMVC.ViewModels.TechnicianViewModel>
<div class="row">
#foreach (var item in Model)
{
<div class="col-sm-6 col-md-3">
<div class="">
<div class="">
<div class="">
#item.UserName
</div>
<div class="">
Technician
</div>
</div>
<div class="">
<img src="~\imagesurl-#item.GenerateName()" class="img-responsive" alt="...">
</div>
<div class="">
<p class="overlay__desc">
#item.Bio
</p>
<ul class="overlay__social">
<li><i class="ion-social-twitter"></i></li>
<li><i class="ion-social-facebook"></i></li>
<li><i class="ion-social-skype"></i></li>
<li><i class="ion-social-whatsapp-outline"></i></li>
</ul>
More info
</div>
</div>
</div>
}
</div> <!-- / .row -->
Here is the View Model :-
public class TechnicianViewModel
{
public Guid ID { get; set; }
public string UserName { get; set; }
public string Bio { get; set; }
public string GenerateName()
{
string str = GenerateURL();
str = str + ".jpg";
return str;
}
public string GenerateURL()
{
string phrase = string.Format("{0}", UserName);
string str = phrase.ToLower();
str = Regex.Replace(str, #"\s", "-");
return str;
}
}
How can I avoid my controller method being an [HttpGet] as I had implemented here so that I can have the ID from the viewmodel object returned by the view.
[HttpGet]
[Route("technician/profile/calgary-{url}")]
public IActionResult Profile(Guid? ID,string url)
{
var Profile = unitOfWork.TechnicianRepository.GetByGuidId(ID);
return View(Profile);
}
In your View, change the link to the following:
More info
You can get rid of the HttpGet and Route decorators on your controller method. Those will be taken care of by the default routing config:
public ActionResult Profile(string id)
{
TempData["guid"] = id;
return RedirectToAction("Profile");
}
public ActionResult Profile()
{
Guid guid = Guid.Parse(TempData["guid"]);
var Profile = unitOfWork.TechnicianRepository.GetByGuidId(guid);
return View(Profile);
}

ASP.Net Display image in view using Umbraco CMS (Archetype)

So I'm using Umbraco CMS with Archetype and trying to get an image property to display on the frontend. I have it displaying my other 3 fields as per attached image but I'm struggling to show it for the mediaitem, what am I doing wrong
// HomeController.cs
public class HomeController : SurfaceController {
public ActionResult RenderTheGroup()
{
List<FeaturedItem> model = new List<FeaturedItem>();
IPublishedContent homepage = CurrentPage.AncestorOrSelf(1).DescendantsOrSelf().Where(x => x.DocumentTypeAlias == "home").FirstOrDefault();
ArchetypeModel featuredItems = homepage.GetPropertyValue<ArchetypeModel>("featuredItemList");
foreach(ArchetypeFieldsetModel fieldset in featuredItems)
{
int imageId = fieldset.GetValue<int>("image");
var mediaItem = Umbraco.Media(imageId);
string image = mediaItem.Url;
model.Add(new FeaturedItem(
fieldset.GetValue<string>("name"),
fieldset.GetValue<string>("paragraph"),
fieldset.GetValue<string>("link"),
image
));
}
return PartialView(PARTIAL_VIEW_FOLDER + "_TheGroup.cshtml", model);
}
}
// Model - FeaturedItem.cs
public class FeaturedItem
{
public string Name { get; set; }
public string Paragraph { get; set; }
public string Image { get; set; }
public string LinkUrl { get; set; }
public FeaturedItem(string name, string paragraph, string image, string linkUrl)
{
Name = name;
Paragraph = paragraph;
Image = image;
LinkUrl = linkUrl;
}
}
}
// View
<div class=" col-md-3">
<div class="thumbnail">
#RenderFeaturedItem(#Model[0], null)
</div>
</div>
#helper RenderFeaturedItem(FeaturedItem item, string extraClass)
{
<img src="#item.Image" alt="">
<div class="">
<div class="caption">
<h4>
<a target="_blank" href="#item.LinkUrl">#item.Name</a>
</h4>
<p>#item.Paragraph</p>
</div>
<div class="">
<p>
<a target="_blank" href="#item.LinkUrl">
Link here
<i class="fa fa-chevron-right" aria-hidden="true"></i>
</a>
</p>
</div>
</div>
}
I don't know if it would still be helpful to you but I solved this problem the following way:
int imageId = fieldset.ToPublishedContent().GetPropertyValue<int>("image");
var mediaItem = Umbraco.Media(imageId);
string image = mediaItem.Url;

How to get Model List in Controller

I have this form in MVC Razor . The html is quite long so I am posting the area where I want to work
these are the checkboxes which are populated as service packages
The flow is the user will upload a photo and when proceeds to the next step it goes to a page where he will be selecting service for each photo if he has uploaded 3 photos the three photos will be having the same service
listing but different order IDS
I want is that when a user select services for a specific order means a specific order has multiple services . I want to map it so that Model List will be feteched in the Controller and I can easily insert in the database
this is the HTML:
#using (Html.BeginForm("PlaceOrder", "User", FormMethod.Post, new { id="ServiceForm",#class = "form-horizontal
white-clr", role = "form" }))
{
<!--If user has uploaded a single photo or multiple photo -->
<div class="window-for-choose-service">
#if (ViewBag.OrdersList != null)
{
int i= 1;
foreach (var d in ViewBag.OrdersList)
{
<div class="row">
<div class="col-sm-3 col-md-3 col-lg-3">
<img src="#d.ThumbnailPath" class="img-thumbnail img-responsive" width="250">
</div>
<div class="col-sm-9 col-md-9 col-lg-9">
<form class="white-clr" role="form">
<div class="form-group">
<label for="name">Description</label>
<textarea class="form-control" rows="4"></textarea>
</div>
</form>
</div>
<div class="col-sm-12 col-md-12 col-lg-12">
<div class="panel-group" id="accordion_#d.ID">
<div class="panel panel-primary">
#foreach (var Services in ViewBag.ServicePackages)
{
int cID = Services.ID + d.ID;
//int rndNumber = Convert.ToInt32(TimeSpan.FromSeconds(new Random().Next(0,
11221)).ToString("hmsf"));
if (Services.ServiceParentID == null)
{
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion_#d.ID"
href="#collapseOne_#cID">
#Services.ServiceName
</a>
</h4>
</div>
<div id="collapseOne_#cID" class="panel-collapse collapse in">
<div class="panel-body">
<div>
<div class="table-responsive">
#foreach (var child in Services.ft_service_packages1)
{
//string ness = "ServiceSelected[" + #d.ID + "]";
<div style="width:auto;min-width:250px;float:left; padding:4px; display:inline-block">
<div style="float:left;padding-right:5px;">
<label for="inlinecheckbox_#child.ID">
#Html.CheckBoxFor(m => m.ServiceSelect, new { id = "inlinecheckbox_" +
#child.ID, price_attr = "#child.ServicePrice"})
#Html.HiddenFor(m => m.UploadOrderID, new { Value = #d.ID })
</label>
</div>
<div style="padding-left:2px;">#child.ServiceName</div>
</div>
}
</div>
</div>
</div>
</div>
i++;
}
}
</div>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12"><p class="text-right font-blue"><b> Price $
0.0</b></p> </div>
</div>
}
}
The Html is genereting perfectly fine . But the thing is not getting anything in the controller regarding the model
Model is listed below
using System;
using System.Collections.Generic;
public partial class ft_order_itemized
{
public int ID { get; set; }
public int UploadOrderID { get; set; }
public int ServiceSelected { get; set; }
public decimal ServiceCharges { get; set; }
public System.DateTime ServiceSelectedDate { get; set; }
public Nullable<int> OrderID { get; set; }
public bool ServiceSelect { get; set; }
public virtual ft_orders ft_orders { get; set; }
public virtual ft_service_packages ft_service_packages { get; set; }
public virtual ft_uploads_orders ft_uploads_orders { get; set; }
}
My Controller :
[HttpPost]
public ActionResult PlaceOrder(ICollection<ft_order_itemized> Orders)
{
if (Orders.Count > 0)
{
}
// ICollection Allstrings = Orders["Service"].ToList();
return View();
}

Categories

Resources