Remove records from database using Entity Framework - asp.net-mvc

I am trying to remove records from database using Entity Framework.
This is the code:
Controller:
[HttpPost]
public ActionResult DeleteProduct(int?id)
{
Product prd = db.Products.Find(id);
db.Products.Remove(prd);
db.SaveChanges();
return View();
}
View:
<form method="post" enctype="multipart/form-data">
<div class="row ">
#foreach (var product in Model)
{
<div class="col-md-6 col-lg-4 Products">
<figure class="card card-product mehsul">
<div class="img-wrap"> <img class="img-fluid mehsulimg" src="#product.PhotoProducts.First().ImageName" alt=""> </div>
<div class="handhover">
<img class="img-fluid" src="#product.PhotoProducts.Last().ImageName" alt="">
</div>
<figcaption class="info-wrap">
#product.ProdName
<p class="desc">Some small description goes here</p>
</figcaption>
<div class="bottom-wrap">
Paylash
<a id="DelProd" href="/ProductAd/DeleteProduct/#product.id" class="m-2 btn btn-sm btn-primary float-right">Sil</a>
<div class="price-wrap h5">
<span class="price-new">$1280</span> <del class="price-old">$1980</del>
</div> <!-- price-wrap.// -->
</div> <!-- bottom-wrap.// -->
</figure>
</div> <!-- col // -->
}
</div>
</form>
But I am getting this error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /ProductAd/DeleteProduct/1

If You are sending a delete request, it is not a [HTTPPost] and you are passing the whole model to the controller not only the key, so if you need to add id in your request, you should do something like this.
API Version:
[HttpDelete("{id}")]
public ActionResult DeleteProduct(int?id)
{
Product prd = db.Products.Find(id);
db.Products.Remove(prd);
db.SaveChanges();
return View();
}
Or using something like this for MVC Version with full model
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(YourViewModel viewModel)
{
var id = viewModel.id;
Product prd = db.Products.Find(id);
db.Products.Remove(prd);
db.SaveChanges();
return View();
}

Since your action has the "HttpPost" attribute, you need to do an HTTP POST. Your a tag would only do a GET, and the server would reject it as a page not found. Assuming everything else is correct, then I think it would be something more like this:
<div class="row ">
#foreach (var product in Model)
{
<div class="col-md-6 col-lg-4 Products">
<figure class="card card-product mehsul">
<div class="img-wrap"> <img class="img-fluid mehsulimg" src="#product.PhotoProducts.First().ImageName" alt=""> </div>
<div class="handhover">
<img class="img-fluid" src="#product.PhotoProducts.Last().ImageName" alt="">
</div>
<figcaption class="info-wrap">
#product.ProdName
<p class="desc">Some small description goes here</p>
</figcaption>
<div class="bottom-wrap">
Paylash
<form method="post" action="#Url.Action("DeleteProduct","ProductAd", new {id=productid})">
<button type="submit" class="m-2 btn btn-sm btn-primary float-right">Sil</a>
</form>
// or
#using(Html.BeginForm("DeleteProduct","ProductAd",new {id=product.id}))
{
<button type="submit" class="m-2 btn btn-sm btn-primary float-right">Sil</a>
}
<div class="price-wrap h5">
<span class="price-new">$1280</span>
<del class="price-old">$1980</del>
</div> <!-- price-wrap.// -->
</div> <!-- bottom-wrap.// -->
</figure>
</div> <!-- col // -->
}
</div>

Related

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1 .

Welcome,
I have several pictures, when I click on one it should take me to another window of this picture.
But this does not happen, but I get this window with this error message:
The model item passed into the dictionary is of type
'System.Collections.Generic.List`1[FirstProject.Models.student]', but
this dictionary requires a model item
I will put the codes related to the problem:
HomeController
using FirstProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FirstProject.Controllers
{
public class HomeController : Controller
{
level_8_coursesEntities db = new level_8_coursesEntities();
public ActionResult Index()
{
List<level_8_courses> list = db.level_8_courses.ToList();
return View(list);
}
public ActionResult Numberofstudents()
{
List<level_8_courses> list = db.level_8_courses.ToList();
return View(list);
}
public ActionResult Students(int? id)
{
List<student> studentlist = null;
if (id.HasValue)
{
studentlist = db.students.Where(x => x.corId == id).ToList();
}
else
{
// Set the `studentlist` to some default value when `id` doesn't defined or not a number.
studentlist = null;
}
return View(studentlist);
}
Number of students.chtml
#{
ViewBag.Title = "Numberofstudents";
}
#using FirstProject.Models;
#model List<level_8_courses>
<div class="container">
<section class="page-section portfolio" id="portfolio">
<div class="container">
<!-- Portfolio Section Heading-->
<h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Numberofstudents</h2>
<!-- Icon Divider-->
<div class="divider-custom">
<div class="divider-custom-line"></div>
<div class="divider-custom-icon"><i class="fas fa-star"></i></div>
<div class="divider-custom-line"></div>
</div>
<!-- Portfolio Grid Items-->
<div class="row justify-content-center">
<!-- Portfolio Item 1 data-bs-target="#portfolioModal" -->
#foreach (var item in Model)
{
<div class="col-md-6 col-lg-4 mb-5">
<a href="/Home/students/#item.Id">
<div class="portfolio-item mx-auto" data-bs-toggle="modal">
<div class="portfolio-item-caption d-flex align-items-center justify-content-center h-100 w-100">
<div class="portfolio-item-caption-content text-center text-white"><i class="fas fa-plus fa-3x"></i></div>
</div>
<img class="img-fluid" style="height:100px;width:100px" src="#item.photo" alt="" />
</div>
</a>
<div style="text-align:center">
<h5>#item.corName</h5>
</div>
</div>
}
</div>
</div>
</section>
</div>
Students.chtml
#using FirstProject.Models;
#model List<student>
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="card col-sm-6">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="..." alt="Card image cap">
<div class="card-body">
<h5 class="card-title">#item.sName</h5>
<p class="card-text">#item.sEmail</p>
</div>
</div>
</div>
}
</div>
</div>
Thanks
fix students action, if you don't have any students create an empty list as a model, and remove studentlist = null;
List<student> studentlist = null
if (id!=null && id > 0)
studentlist = db.students.Where(x => x.corId == id).ToList();
if(studentlist==null) studentslist= new List<student>();
return View(studentlist);

How to display only one image in the view from multiple images on the database? (ASP.NET MVC)

I have multiple images for one product on the database. I created two tables. One for Products and another for Photos of products. And I want to show only one photo on the page. My code is below. I have tried to declare variable in the view. But there is error:
PhotoProduct' is a type, which is not valid in the given context
Is there other way for that?
Here is my code:
#foreach (Product prd in Model.Prod.Where(i => i.userid == Model.userr.ID))
{
<div class="col-md-4">
<figure class="card card-product mehsul">
#PhotoProduct prphoto = Model.Photopr.Where(ph => ph.Product.id == ph.id).Take(1).ToList()
{
<div class="img-wrap"> <img class="img-fluid mehsulimg" src="#prphoto.Photo" alt=""> </div>
}
<div class="handhover">
<img class="img-fluid" src="~/PublicFront/images/serv2b712.jpg" alt="">
</div>
<figcaption class="info-wrap">
<h4 class="title">#prd.ProdName</h4>
<p class="#prd.Price"></p>
</figcaption>
<div class="bottom-wrap">
Order Now
<div class="price-wrap h5">
<span class="price-new">$1280</span>
<del class="price-old">$1980</del>
</div> <!-- price-wrap.// -->
</div> <!-- bottom-wrap.// -->
</figure>
</div> <!-- col // -->
}
I saw your models in this question before Error: Value cannot be null. Parameter name: source.
In your Photo Model you are already declaring PhotoProducts as virtual;
public virtual ICollection<PhotoProduct> PhotoProducts { get; set; }
Using virtual in EntityFramework means that you are "lazy-loading" that entity or that entity gets automatically loaded.
Since it is automatically loaded, you could do;
#foreach (Product prd in Model.Prod.Where(i=>i.userid==Model.userr.ID))
{
// ...
#if(prd.PhotoProducts.FirstOrDefault() != null){
<div class="img-wrap">
<img class="img-fluid mehsulimg" src="#prd.PhotoProducts.First().Photo" alt="">
</div>
}else{
<div class="img-wrap">
<img class="img-fluid mehsulimg" alt="No Photo Available">
</div>
}
// ...
}

Button Submit in MVC is not working as expected

I have a submit button in index.cshtml page and when i click that button i need to go in another ActionResult server method.But it's not working.(not hitting to the server side method)
Html
#model IEnumerable<AAB.Domain.Items>
<!-- Featured Products -->
<div class="card-deck card-deck-product mt-3 mb-2 mb-sm-0">
#foreach (var item in Model)
{
<div class="card card-product" id="#item.ItemId">
<div class="card-body">
<button class="wishlist atw-demo " title="Added to wishlist"><i data-feather="heart"></i></button>
<img class="card-img-top" src="#item.ImageUrl" alt="Card image cap">
#item.ItemName
<div class="price"><span class="h5">Rs:#item.ItemPrice</span></div>
</div>
<div class="card-footer">
<input type="submit" class="btn btn-sm" id="#item.ItemId" value="Add to Cart" href="#Url.Action("AddNewItems","Home",new { ItemId=item.ItemId})"/>
</div>
</div>
}
</div>
Server side
[HttpPost]
public ActionResult AddNewItems(int ItemId)
{
// Some code here.
return PartialView("_PopCart", ItemId);
}
Surround your button with a tag.
<a href="#Url.Action("AddNewItems","Home",new { ItemId=item.ItemId})">
<input type="submit" class="btn btn-sm" id="#item.ItemId" value="Add to Cart" />
</a>

how to show video file in mvc when i have a physical path in my table

i have physical path of video in my database table how can i show those video files in my mvc view. can anyone give me an idea.
here is my service layer in which i am getting all the values in a list
public IEnumerable<Marketing> GetMarketingContents()
{
return fDbContext.Marketings.ToList();
}
view model
public class ViewModelMarketing
{
public List<Marketing> MarketVideo { get; set; }
}
here is my controller in which i am filtering the videos and passing it to the partial view.
public ActionResult MarketingListVideos()
{
ViewModelMarketing viewModelMarketing = new ViewModelMarketing();
var debs = from s in iMarketingService.GetMarketingContents()
select s;
viewModelMarketing.MarketVideo = debs.Where(t => t.MarketingType.Equals("v") && t.Active != false).ToList();
return PartialView("_GetVideos", viewModelMarketing);
}
here is my partial view named _GetVideos
#model PreFlight.ViewModels.ViewModelMarketing
#foreach (var item in Model.MarketVideo)
{
<div class="list-group">
<div class="row">
<div class="col-md-1 col-xs-1">
<i class="glyphicon glyphicon-facetime-video" style="color: black"></i>
</div>
<div class="col-md-5 col-xs-5">
#item.Content
</div>
<div class="col-md-5 col-xs-5">
#item.Active
</div>
</div>
</div>
}
here is my main view in which i am rendering this partial view
#model PreFlight.ViewModels.ViewModelMarketing
<div class="panel-body">
<div class="list-group">
#Html.Action("MarketingListVideos", "Marketing")
</div>
</div>
now i am getting the list of videos in my view. how can i show it as a video files. can any one help me to get this. any help will be appreciated.
You can use HTML5 :
#foreach (var item in Model.MarketVideo)
{
<div class="list-group">
<div class="row">
<div class="col-md-1 col-xs-1">
<i class="glyphicon glyphicon-facetime-video" style="color: black"></i>
</div>
<div class="col-md-5 col-xs-5">
#item.Content
</div>
<div class="col-md-5 col-xs-5">
#item.Active
</div>
<video controls="controls">
<source src="#item.YourVideoPath" type="video/mp4" />
</video>
</div>
</div>
}
And for best pratices you should espeficy the correct extension:
<video controls="controls">
<source src="#item.YourVideoPath" type="video/#item.VideoExtension" />
</video>
Here some referece:
http://www.w3schools.com/html/html5_video.asp
Note: just remember that not all browsers supports the video tag, but a good amount does

<img> element with onclick submits the form instead of firing action

I am having a weird issue in my Login.cshmtl view which I posted below. So on the top right corner of my login page, I have two textboxes for credentials and two .png images as their labels, a "Remember Me" checkbox and a .png image as its label, and finally a "ForgotPassword" .png image defined as:
<img onclick="location.href ='#Url.Action("ForgotPassword", "Account")'" src="~/Content/Images/ForgotPassword.png" />
Everything worked fine until I changed this line as follows:
<input type="image" onclick="location.href ='#Url.Action("ForgotPassword", "Account")'" src="~/Content/Images/ForgotPassword.png" />
Surprisingly, now my image-button is broken and it submits the page! Using the debugger I observe that POST method of my Login action is called instead of ForgotPassword action. Can you please explain how this happens? Below, I am posting the Login.cshtml view with irrelevant parts removed.
#model FooProject.Web.ViewModels.LoginViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="navbar navbar-fixed-top">
<div class="navbar-header">
<input type="image" class="navbar-brand" onclick="location.href ='#Url.Action("Index", "Home")'" src="~/Content/Images/logo.png"/>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav" style="margin:10px">
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
<div class="nav navbar-nav navbar-right">
<div class="row">
<div class="col-md-5">
<span class="actionLink">
<img src="~/Content/Images/Username.png"/>
</span>
</div>
<div class="col-md-7">
<span class="actionLink">
<img src="~/Content/Images/Password.png"/>
</span>
</div>
</div>
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "loginForm", #class = "navbar-right form-inline" }))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-5">
#Html.TextBoxFor(m => m.UserName, new { #class = "" })
</div>
<div class="col-md-5">
#Html.PasswordFor(m => m.Password) <br />
</div>
<div class="col-md-2" style="padding-left:0">
<input type="image" alt="Submit" src="~/Content/Images/Login.png" style="width:45px" />
</div>
</div>
<div class="row">
<div class="col-md-5">
#Html.CheckBoxFor(m => m.RememberMe)
<span class="actionLink">
<img src="~/Content/Images/RememberMe.png" style="height:11px;vertical-align:top;margin-top:2px" />
</span>
</div>
<div class="col-md-7">
<img onclick="location.href ='#Url.Action("ForgotPassword", "Account")'" src="~/Content/Images/ForgotPassword.png" />
</div>
</div>
}
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<input type="image"> works as submit button, so this is expected behavior.
But there is solution:
<input type="image" onclick="location.href ='#Url.Action("ForgotPassword", "Account")'; return false;" src="~/Content/Images/ForgotPassword.png" /> will do the trick.
By adding return false; you prevent submission from being executed.
There is also alternative solution:
There is no reason to replace img tag with input. If you want to see cursor on hover, you can do it with CSS:
img.submit:hover {
cursor: pointer;
}
and decorate img with submit class:
<img class="submit" onclick="location.href ='#Url.Action("ForgotPassword", "Account")'" src="~/Content/Images/ForgotPassword.png" />
And the way I would do that:
<a href='#Url.Action("ForgotPassword", "Account")'>
<img src="/Content/Images/ForgotPassword.png" />
</a>
By changing the image tag to an input tag you've create an image as a submit button and it's doing what you should expect: submitting the form with the action and method defined.
See http://www.w3schools.com/tags/att_input_type.asp for more information
From the W3C Wiki (emphasis is mine):
The image button state represents either an image from which a user
can select a coordinate and submit the form, or alternatively a button
from which the user can submit the form. The element is a button,
specifically a submit button

Resources