Product image not showing in asp.net c#
I am creating an online flower shopping site. I want to view the products to shop on the product page, but the problem is that the image does not appear in the product on the products page, but I can see it in the image file ProductImages
.
Table tblProductImage
:
CREATE TABLE [dbo].[tblProductImage]
(
[PIMGID] INT IDENTITY (1, 1) NOT NULL,
[PID] INT NOT NULL,
[Name] NVARCHAR (MAX) NULL,
[Extention] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([PIMGID] ASC),
CONSTRAINT [FK_tblProductImages_ToProductt]
FOREIGN KEY ([PID]) REFERENCES [dbo].[tblProducts] ([PID])
);
Products.aspx
:
<div class="container">
<div class="row" style="padding-top: 50px">
<asp:Repeater ID="rptrProducts" runat="server">
<ItemTemplate>
<div class="col-sm-3 col-md-3">
<a style="text-decoration: none;" href="ProductsView.aspx?PID=<%#Eval("PID") %>">
<div class="img-thumbnail">
<img class="img-fluid" src="Images/ProductImages/<%#Eval("PID") %>/<%#Eval("ImageName") %><%#Eval("Extention") %>" alt="<%#Eval("ImageName") %>">
<div class="p-2">
<div class="probrand pb-1"><%#Eval("CatgName") %></div>
<div class="proName"><%#Eval("PName") %></div>
<div class="proPrice"><span class="proOgPrice"><%#Eval("PPrice") %></span> <%#Eval("PSelPrice") %> <span class="proPriceDiscount">(<%#Eval("DiscAmount") %> Off)</span></div>
</div>
</div>
</a>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
Code-behind Products.aspx.cs
:
protected void Page_Load(object sender, EventArgs e)
{
BindProductRepeater();
}
private void BindProductRepeater()
{
String CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
Int64 CatId = Request.QueryString["cat"] == null ? 0 : Convert.ToInt64(Request.QueryString["cat"]);
Int64 SubCatId = Request.QueryString["subcat"] == null ? 0 : Convert.ToInt64(Request.QueryString["subcat"]);
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("procBindAllProducts", con))
{
cmd.CommandType = CommandType.StoredProcedure;
if (CatId > 0)
{
cmd.Parameters.AddWithValue("@PCategoryID", CatId);
}
if (SubCatId > 0)
{
cmd.Parameters.AddWithValue("@PSubCatID", SubCatId);
}
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dtBrands = new DataTable();
sda.Fill(dtBrands);
rptrProducts.DataSource = dtBrands;
rptrProducts.DataBind();
}
}
}
}
Stored procedure procBindAllProducts
:
CREATE PROCEDURE [dbo].[procBindAllProducts]
(@PCategoryID int = NULL,
@PSubCatID int = NULL)
AS
SELECT
A.*, B.*,
C.CatName,
A.PPrice - A.PSelPrice AS DiscAmount, B.Name AS ImageName,
C.CatName AS CatgName
FROM
tblProducts A
INNER JOIN
tblCategories C ON C.CatID = A.PCategoryID
CROSS APPLY
(SELECT TOP 1 *
FROM tblProductImage B
WHERE B.PID = A.PID
ORDER BY B.PID DESC) B
WHERE
A.PCategoryID = COALESCE(NULLIF(@PCategoryID, NULL), A.PCategoryID)
AND A.PSubCatID = COALESCE(NULLIF(@PSubCatID, NULL), A.PSubCatID)
ORDER BY
A.pid DESC
RETURN 0
See also questions close to this topic
-
How can I determine the correct zoom level for Bing Maps when there is only one pushpin?
I add a number of pushpins to a map and then "rightsize" or "right zoom" it so that all the pushpins show but so that the ones on the far edges are barely within the boundaries, like so:
However, if there is only one pushpin (as in the following case with Iowa, which only had the one civil war battle), rather than zero in on that as close as possible, it zooms out all the way to Skylab, like so:
This is the code I use to "right size" the map:
private void RightsizeZoomLevelForAllPushpins() { try { // Set the view so that all pushpins are displayed, with a bit of a margin around them // from https://stackoverflow.com/questions/65779504/how-to-set-the-zoom-level-of-bing-map-to-just-wide-enough-to-display-all-pushpin/65781319#65781319 var map = this.userControl11.myMap; var locations = map.Children.OfType<Pushpin>().Select(x => x.Location); //Margin var w = new Pushpin().Width; var h = new Pushpin().Height; var margin = new Thickness(w / 2, h, w / 2, 0); //Set view map.SetView(locations, margin, 0); currentZoomLevel = Convert.ToInt32(map.ZoomLevel); UncheckAllZoomLevelToolstripMenuItems(); SetZoomMenuItem(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } }
How can I get a one-pushpin map to not only center, but also zoom in as far as possible?
-
C#: calling methods with multiple objects as parameters from other classes
I am wondering whether it is possible to call methods with
objects
as parameters from otherclasses
without using to many parameters.In detail: how can you call method
Info.Status()
insideclass Car
?Extending parameters to
MethodA(Location location1, Location location2, Garage garage1, Car car1)
would do the trick.
BUT whenever you use
MethodA()
somewhere else, you always have to deal with all parameters and objects, just because of the methodInfo.Status()
in it, that needs the additional parameters.Or is it a lack of structure of my code and you need other principles (out, Interface, ...) ?
And where you should create the
objects
location1, location2, garage1 and car1 ? InMain
?Lovely greetings from Germany,
Laurapublic class Location { } public class Garage {} public class Car { public void MethodA(Location location1, Location location2) { // method doing stuff with objects location1 and location2 // now calling method Info.Status() to get some status information } } public static class Info { public static void Status(Location location1, Location location2, Garage garage1, Car car1) { // method to print out some values and properties of objects location1, location2, // garage1 and car1 } }
-
I am trying to create a Notepad application in C# that uses a SQL database. How to cross references users with another table?
I am trying to create a Notepad application in C# that uses a SQL database to allow users to log in and access previously-stored notes. How would I go about this? I am trying to develop an application that will work locally on someone's computer but can log in with different usernames and passwords to store different notes. For example, bobPersonal123 has 20 different notes, where each note has a Title, Message, and Picture. Bob also has a work account, bobWork123, that has a different set of notes, let's say 15, each with a Title, Message, and Picture. I know how to use a separate SQL table for each aspect, logging in with different accounts and storing 20 different Title, Message, and Pictures, but how would I be able to allow a specific user to access a specific table of notes once logged in? Would I essentially need to create a table within a table? Or is there a way to create a column for bobPersonal vs bobWork that contains some sort of reference to another table? If so, how do you create references to other tables?
Sorry if this question has a fairly obvious answer as I've only just begun using SQL. Thanks in advance.
-
getting prob on reading nested class c#
Hi really need assistance here,
I have 2 classes which i use to read from json i need to save into 2 tables (root and participants) in 1 submission. i will have only 1 root with 1 or many participants. i have no prob saving the root but i have prob reading if i am sending both (root with participants}
[ { "NoIC": "122233243", "Nama": "TEST NAME", ... "Participant": [ { "Nama" : "Participant 1", "Bil" : "1", ... }, { "Nama" : "Participant 2", "Bil" : "1", .... } ] } ] public class Participant { public string ref_no { get; set; } public string Nama { get; set; } public string Bil { get; set; } public string Price { get; set; } public string RequestedPlace { get; set; } public string RequestedExe { get; set; } public string RequestedDate { get; set; } public string Type { get; set; } } public class Root { public string NoIC { get; set; } public string Nama { get; set; } public string HPNo { get; set; } public string Email { get; set; } public string Type { get; set; } public string RegisterBy { get; set; } public List<Participant> Participant { get; set; } } public string RegisterApplication([FromBody] Root register, Participant participants) { try { using (MySqlConnection sql = new MySqlConnection(_connectionString)) { using (MySqlCommand cmd = new MySqlCommand("GetInsertApplication", sql)) { sql.Open(); cmd.CommandType = System.Data.CommandType.StoredProcedure; // cmd.Parameters.AddWithValue("@refNo", register.RefNo); cmd.Parameters.AddWithValue("@NoIC", register.NoIC); cmd.Parameters.AddWithValue("@Nama", register.Nama.ToUpper()); cmd.Parameters.AddWithValue("@NoFonHp", register.HPNo); cmd.Parameters.AddWithValue("@Email", register.Email); cmd.Parameters.AddWithValue("@refType", register.Type); cmd.Parameters.AddWithValue("@RegisterBy", register.RegisterBy); ...... ref_no = refnoParameter.Value.ToString(); //will pass this refno to child/participant
my prob is here. i need to read the child (1 Root can have more than 1 participant)
List<Participant> participants = new List<Participant>(); using (MySqlCommand cmd2 = new MySqlCommand("GetInsertParticipant", sql)) { cmd2.Parameters.AddWithValue("@ref_no", ref_no); cmd2.Parameters.AddWithValue("@Nama", participant.Nama.ToUpper()); cmd2.Parameters.AddWithValue("@Bil", participant.Bil); cmd2.Parameters.AddWithValue("@Price", participant.Price); cmd2.Parameters.AddWithValue("@RequestedPlace", participant.RequestedPlace); cmd2.Parameters.AddWithValue("@RequestedExe", participant.RequestedExe); cmd2.Parameters.AddWithValue("@RequestedDate", participant.RequestedDate); cmd2.Parameters.AddWithValue("@Type", participant.Type); cmd2.Connection.Open(); cmd2.CommandType = CommandType.Text; cmd2.ExecuteNonQuery();
}}}}}
anybody please, i stuck here for few days and i really need your help/opinion. thaks in advanced
-
How do I insert input from form to database?
My model looks like this:
public class Customer { public int CustomerId { get; set; } [Required(ErrorMessage = "Please enter a valid first name")] public string FirstName { get; set; } [Required(ErrorMessage = "Please enter a valid last name")] public string LastName { get; set; } [Required(ErrorMessage = "Please enter a valid address")] public string Address { get; set; } public string Email { get; set; } [Required(ErrorMessage = "Please enter a valid city")] public string City { get; set; } public string Phone { get; set; } [Range(1, 5, ErrorMessage = "Please enter a valid country")] public int CountryId { get; set; } public Country Country { get; set; } [Required(ErrorMessage = "Please enter a valid state")] public string State { get; set; } [Required(ErrorMessage = "Please enter a valid postal code")] public string PostalCode { get; set; } public string fullname => FirstName + LastName; }
My controller looks like this:
public class CustomerController : Controller { private CustomerContext context { get; set; } public CustomerController(CustomerContext ctx) { context = ctx; } public IActionResult List() { var customers = context.Customers.ToList(); return View(customers); } [HttpGet] public IActionResult Add() { ViewBag.Action = "Add"; ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList(); return View("Edit", new Customer()); } [HttpGet] public IActionResult Edit(int id) { ViewBag.Action = "Edit"; ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList(); var customer = context.Customers .Include(c => c.Country) .FirstOrDefault(c => c.CustomerId == id); return View(customer); } [HttpPost] public IActionResult Edit(Customer customer) { string action = (customer.CustomerId == 0) ? "Add" : "Edit"; if (ModelState.IsValid) { if (action == "Add") { context.Customers.Add(customer); } else { context.Customers.Update(customer); } context.SaveChanges(); return RedirectToAction("List", "Customer"); } else { ViewBag.Action = action; ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList(); return View(customer); } }
I also have a DbContext file with data i created to test other things:
public class CustomerContext : DbContext { public CustomerContext(DbContextOptions<CustomerContext> options) :base(options) { } public DbSet<Customer> Customers { get; set; } public DbSet<Country> Countries { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Country>().HasData( new Country { CountryId = 1, Name = "Canada"}, new Country { CountryId = 2, Name = "United States"}, new Country { CountryId = 3, Name = "United Kingdom" }, new Country { CountryId = 4, Name = "Mexico" }, new Country { CountryId = 5, Name = "Russia" } ); modelBuilder.Entity<Customer>().HasData( new Customer { CustomerId = 1, FirstName = "Bruce", LastName = "Wayne", Phone = "416-123-4567", Email = "bruce.wayne@gmail.com", CountryId = 1, Address = "123 sesame street", City = "Toronto", PostalCode = "L812A", State = "Ontario" } ); }
I already did the add-migration and updated my database via the package manager console. I created a form in the view that looks like this:
Cancel<form method="post" asp-action="Add"> <div asp-validation-summary="All"> <div> <label asp-for="FirstName">First Name</label> <input type="text" name="FirstName" asp-for="FirstName" /> </div> <div> <label asp-for="LastName">Last Name</label> <input type="text" name="LastName" asp-for="LastName" /> </div> <div> <label asp-for="Address">Address</label> <input type="text" name="Address" asp-for="Address" /> </div> <div> <label asp-for="City">City</label> <input type="text" name="City" asp-for="City" /> </div> <div> <label asp-for="State">State</label> <input type="text" name="State" asp-for="State" /> </div> <div> <label asp-for="PostalCode">Postal Code</label> <input type="text" name="Postal Code" asp-for="PostalCode" /> </div> <div> <label asp-for="CountryId">Country</label> <select name="Country" asp-for="CountryId"> @foreach (Country country in ViewBag.Countries) { <option value="@country.CountryId">@country.Name</option> } </select> </div> <div> <label asp-for="Email">Email</label> <input type="text" name="Email" asp-for="Email" /> </div> <div> <label asp-for="Phone">Phone</label> <input type="text" name="Phone" asp-for="Phone" /> </div> <input type="hidden" asp-for="CustomerId" /> </div> <button type="submit" value="Save" asp-controller="Customer" asp-action="List">Save</button>
I've tried looking up multiple different solutions to solve my issue but I cant seem to figure out how to solve it. If someone could help me that would be much appreciated. thanks in advance.
-
Submit button doenst work with script asp.net mvc5
I have a maybe simple problem but I don`t have that much experience with scripts:
I have this Skript in my _Layout.cshtml:
<script> $('button').click(function () { $(this).prop('disabled', true); }); </script>
and one of my views:
@using (Html.BeginForm("Create", "Home", FormMethod.Post, null)) { @Html.AntiForgeryToken() <div class="mt-5 d-flex flex-row"> <textarea class="form-control" name="TextArea"></textarea> <button class="btn btn-secondary btn-block mt-2 post-btn" type="submit" id="PostButton">Post</button> </div> }
This form works great without the script, but for any reason with the script it doesn`t work.
I placed the script in the _layout.cshtml because I want to have it for all buttons in my asp.net page.
After click on the button the button is disabled - as I wish - but the action result "Create" in the HomeController will not called.
I think I need to extend the script but can someone help me how to do it?
Thanks all
-
Supposed to take values from html form and display in SQL Server database using Visual Studio 2019 without using any frameworks
As I have learnt to take values from code itself in Visual Studio 2019 using CRUD operation which connects to SQL Server by using pyodbc. I need to take the values from html form and display to the SQL Server database.
Any help will be helpful.
Thank you.
-
Aggregate and reset data in high frequency table
I can't seem to find anything even remotely regarding this topic though I'm sure something must exist.
I'm working with a table that is updated at a reasonably high frequency, the table has thousands of records, each being updated around 2-3 times per second. It contains signaling data (let's call it "usage data" for the sake of simplicity).
I want to aggregate the data in the "usage" column and then reset the value in each record.
My "Device Usage" and "Aggregated Usage" tables would look something similar to this sample:
SET XACT_ABORT, NOCOUNT ON; GO IF ( OBJECT_ID( N'[dbo].[DeviceUsage]' ) IS NOT Null ) DROP TABLE [dbo].[DeviceUsage]; IF ( OBJECT_ID( N'[dbo].[AggregatedUsage]' ) IS NOT Null ) DROP TABLE [dbo].[AggregatedUsage]; GO -- Device Usage Table. CREATE TABLE [dbo].[DeviceUsage] ( [Device] uniqueidentifier NOT NULL, -- Name of the device we're tracking. [Heartbeat] datetimeoffset(4) NOT NULL -- Date / time of the last update to the record. DEFAULT SYSDATETIMEOFFSET(), [Usage] bigint NOT NULL -- Usage count of the specific device. DEFAULT 0, PRIMARY KEY CLUSTERED ( [Device] ASC ) ); -- Aggregated Usage Table. CREATE TABLE [dbo].[AggregatedUsage] ( [Date] date NOT NULL -- Date being recorded. DEFAULT SYSDATETIMEOFFSET(), [Usage] bigint NOT NULL -- Aggregated usage. DEFAULT 0, PRIMARY KEY CLUSTERED ( [Date] ASC ) );
A working sample of how records would be updated would look something like this:
SET XACT_ABORT, NOCOUNT ON; GO -- Insert device record. DECLARE @Device uniqueidentifier = NEWID(); INSERT INTO [dbo].[DeviceUsage] ( [Device] ) SELECT @Device; -- Device usage increment. DECLARE @Counter int = 0; WHILE @Counter < 1000000 BEGIN BEGIN TRANSACTION; UPDATE [dbo].[DeviceUsage] SET [Heartbeat] = SYSDATETIMEOFFSET() , [Usage] += 1 WHERE [Device] = @Device; COMMIT TRANSACTION; SET @Counter += 1; END
And finally I expect the aggregation function to look something akin to this:
SET XACT_ABORT, NOCOUNT ON; GO BEGIN TRANSACTION; -- Collect the aggregated use. MERGE INTO [dbo].[AggregatedUsage] target USING ( SELECT CONVERT( date, SYSDATETIMEOFFSET() ), SUM( [Usage] ) FROM [dbo].[DeviceUsage] ) AS source ( [Date], [Usage] ) ON ( target.[Date] = source.[Date] ) WHEN MATCHED THEN UPDATE SET [Usage] += source.[Usage] WHEN NOT MATCHED THEN INSERT ( [Date], [Usage] ) VALUES ( source.[Date], source.[Usage] ); -- Reset usage. UPDATE [dbo].[DeviceUsage] SET [Usage] = 0; COMMIT TRANSACTION; SELECT * FROM [dbo].[AggregatedUsage]; SELECT * FROM [dbo].[DeviceUsage];
I'm hoping to confirm whether this is a solid foundation for building out a design like this or whether there is a better way to do it, especially with regards to record locks, etc. I believe I have correctly defined the transactions but I'd appreciate any comments regarding my design.
Much appreciated.
-
SonarQube. Parse error in CROSS APPLY with union but all looks good
I have file with sql function about 1k lines. Sonar throws an error on this file. The code itself works without errors. Here is a general view of the request where the error. Parse error message points to symbol above '^'
INSERT INTO foo SELECT ... FROM foo JOIN .. JOIN ... CROSS APPLY (SELECT TOP (1) ... FROM ... WHERE ... ORDER BY .. UNION ^ SELECT TOP (1) ... FROM ... JOIN ... JOIN ... WHERE ... ORDER BY ... ) pp
-
How to add an image after clicking a button using Javascript?
I want to add an image By clicking the button ("click here to discover"). How can I do it? this is the code:
<!DOCTYPE html> <html> <head> <title>Benefit of the month</title> <h1>Benefit of the month</h1> <style> p { background-color:rgb(137, 204, 152); } h1 { background-color:rgb(244, 143, 170); } h1 { color:rgb(74, 35, 13);font-family: sans-serif; } </style> <meta charset="utf-8" /> </head> <body> <script type="text/javascript"> function textchange(id="benefit"){ document.getElementById('b').innerHTML = 'free food bag!'; } </script> <p>And the benefit of the month is... <span id="b">...</span></p> <input type="button" onclick="textchange()" value="click here to discover" /> </script> </body> </html>
-
Can not load images from List of images after reloading the page - Xamarin Forms
I have a problem with loading images from list of images when I have my page reloaded.
This is my list:
public static List<Image> PublicGalleryImages = new List<Image>();
This is how I add images to the list:
Image image1 = new Image(); Stream stream = new MemoryStream(data.ToArray()); image1.Source = ImageSource.FromStream(() => stream); PublicGallery.PublicGalleryImages.Add(image1);`
And this is how I try to load images in the new page with the following code:
foreach (Image img in PublicGalleryImages) container.Children.Add(img);
Do you have any ideas what may cause the problem?
-
SwiftUI: How to store the path to an Img thats in Firebase Storage in Cloud Firestore?
So I use this code to upload an image to firebase storage, which works fine.(If it can be improved then let me know)
But how can I store the path to the image that is in storage in cloud Firestore, so I later can access it and display the Image together with some other Data I have in Firestore.
func uploadImage(image: UIImage) { if let imageData = image.jpegData(compressionQuality: 1) { let storage = Storage.storage().reference().child("Tester/Image0") storage.putData(imageData, metadata: StorageMetadata()) { (metaData, err) in if let err = err { print("an error has occured \(err.localizedDescription)") } else { print("Image has succesfully been uploaded") print(metaData ?? "COULD NOT FIND ANY METADATA") } } } }
-
Combine product attribute based on selection and compatibility
I'm trying generate cross-dependent product attribute dropdown-list.
With chosen option (from dropdown list) system generate appropriate variant id (based on chosen product attribute combinations from droplist).
Example: https://imgur.com/a/fXIMIcf
We have product X with SIZE and COLOR:
- 45mm, black
- 45mm, green
- 60mm, black
- 80mm, black
When we chose size 45mm, COLOR attribute droplist needs to be updated to black and green. And when we chose 60mm there will be only black option in COLOR.
My question is - How is possible to get variant id based on my selection
If you know any demos, tutorials, i would be glad if you'd sent them to me.
Thank you.
-
Manage Woocommerce stock variations for multiple products
Ideally I would like to know if anyone knows a plugin that can do what I need, but if it needs code, I can probably work with it.
So I'm making a Woocommerce shop of handmade clothing and there are multiple products that are made of multiple fabrics. I need one place where I can enter in the total amount of fabric and that will manage the stock for all the products.
Example: The shop offers 3 styles of skirts in 3 different fabrics. There is enough black fabric for 10 skirts so the quantity of each skirt in black is 10. A customer orders skirt #1 in black, so the stock for skirts #1, #2 and #3 in black all need to change to 9 in stock.
Is this possible? I really appreciate any help. Thanks!
-
Woocommerce order products by random except for one
I have a webshop build in Woocommerce where the products are presented in a random order, set in Elementor page builder. This works well, on every page reload the order of products is different, now I only want to exclude one product from this mechanism, and show this single product always as the last product in the list, but I can't find a way to do so.
Does anyone know how to do this?
Thank you in advance