Make List of Items C# MVC [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a very big issuse here. I'm trying to make a list off all cars and push them to View, but it doesn't work as I assume. Any idea how can I do that ?? I would be very thankfull
Here is my Car Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Automarket.Models;
using System.Data.Entity;
using System.Web.Script.Serialization;
using System.Net;
namespace Automarket.Controllers
{
public class CarController : Controller
{
OurDBContext db = new OurDBContext();
private object Viewbag;
private readonly object ds;
// GET: Automarket
public ActionResult Index()
{
List<Marke> marke = db.Marke.ToList();
List<Modeli> modeli = db.Modeli.ToList();
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string deps = oSerializer.Serialize(modeli);
ViewData["deps"] = deps;
ViewData["marke"] = marke;
ViewData["modeli"] = modeli;
return View(db.car.ToList());
}
// GET: Cars/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.car.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
// GET: Cars/Create
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CarID,Make,Model,Price,Registration,Mileage,FuealType,Country,ZipCode,Picture")] Car car)
{
if (ModelState.IsValid)
{
db.car.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
// GET: Cars/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.car.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CarID,Make,Model,Price,Registration,Mileage,FuealType,Country,ZipCode,Picture")] Car car)
{
if (ModelState.IsValid)
{
db.Entry(car).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.car.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
// POST: Cars/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Car car = db.car.Find(id);
db.car.Remove(car);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Here is my Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Automarket.Models
{
public class Car
{
public int CarID { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public float Price { get; set; }
public int Registration { get; set; }
public double Mileage { get; set; }
public string FuealType { get; set; }
public string Country { get; set; }
public int ZipCode { get; set; }
public string pathToImage { get; set; }
}
}

To show a list of objects in your view, bascally, you need:
In Controller, send a list of objects to View using View(<data>) method:
public ActionResult Index() {
OurDBContext db = new OurDBContext();
return View(db.car.ToList());
}
In View, receive the list of objects in Model variable:
#model List<Car>
<html>
...
<body>
#foreach(var item in Model) {
<p>#item.Property</p>
}
</body></html>

Related

DotNet Entity Framework on VSCode Mac -- (Table)Exists() does not exist in current context in Controller

I am following along with the dotnet Microsoft tutorial docs. My one disadvantage is that I'm on a Mac using VS Code. At one point in the tutorial there was a scaffolding command that did not work in VS Code. So far, everything else has worked, but I'm wondering if something is missing in my Controller and that is why I am getting this error. I copy and pasted directly from the Docs. Although, the error infers that it is a syntax issue with the try/catch statement. (which I have reviewed and everything looks in order)
Here is my Controller:
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using virus_mvc.Models;
using System.Text.Encodings.Web;
using virus_mvc.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace virus_mvc.Controllers
{
public class VirusDataController : Controller
{
public async Task<IActionResult> Index()
{
return View(await _context.VirusData.ToListAsync());
}
//
// GET: /HelloWorld/Welcome/
public IActionResult Welcome(string name, int numTimes = 1)
{
ViewData["Message"] = "Hello " + name;
ViewData["NumTimes"] = numTimes;
return View();
}
// GET: VirusData/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var virus = await _context.VirusData
.FirstOrDefaultAsync(m => m.Id == id);
if (virus == null)
{
return NotFound();
}
return View(virus);
}
// GET: Movies/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var virus = await _context.VirusData.FindAsync(id);
if (virus == null)
{
return NotFound();
}
return View(virus);
}
// POST: Movies/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Title,ReleaseDate,Genre,Price")] VirusData virus)
{
if (id != virus.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(virus);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
**if (!VirusDataExists(virus.Id))** -- this is the line throwing the error
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(virus);
}
private readonly virus_mvcContext _context;
public VirusDataController(virus_mvcContext context)
{
_context = context;
}
}
}
Here is my Error:
/Users/katie/C_sharp/virus_backend/virus_mvc/Controllers/VirusDataController.cs(89,26): error CS0103: The name 'VirusDataExists' does not exist in the current context [/Users/katie/C_sharp/virus_backend/virus_mvc/virus_mvc.csproj]
Here's my Model:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using virus_mvc.Data;
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace virus_mvc.Models
{
public class VirusData
{
public int Id { get; set; }
public string Title { get; set; }
[Display(Name = "Release Date")]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
[Column(TypeName = "decimal(18, 2)")]
public decimal Price { get; set; }
}
}

How to retrieve data of nested class instance from parent class instance in ASP.NET Core?

I am trying to modeling a class at school, and I end up with something like this:
public class Class
{
public int ID { get; set; }
public int Grade { get; set; }
public Teacher ClassTeacher { get; set; }
}
This is the Teacher class:
public class Teacher
{
public int ID { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[DataType(DataType.Date)]
public DateTime Birthday { get; set; }
}
When I use scaffolding, migrate and update the database, this is the structure Entity Framework built for me:
dbo.Class:
ID: int
ClassTeacherID: int
Grade: int
dbo.Teacher:
ID: int
Birthday: datetime2(7)
FirstName: nvarchar(MAX)
LastName: nvarchar(MAX)
I want to display the Teacher's FirstName in Views\Classes\Details.cshtml, but the Model.ClassTeacher is null, even after I created a Teacher instance in the database and set ClassTeacherID to the newly created Teacher's ID.
Looking for your helps.
EDIT
ClassesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
namespace WebApplication1.Models
{
public class ClassesController : Controller
{
private readonly WebApplication1Context _context;
public ClassesController(WebApplication1Context context)
{
_context = context;
}
// GET: Classes
public async Task<IActionResult> Index()
{
return View(await _context.Class.ToListAsync());
}
// GET: Classes/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var #class = await _context.Class
.SingleOrDefaultAsync(m => m.ID == id);
if (#class == null)
{
return NotFound();
}
return View(#class);
}
// GET: Classes/Create
public IActionResult Create()
{
return View();
}
// POST: Classes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,Grade")] Class #class)
{
if (ModelState.IsValid)
{
_context.Add(#class);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(#class);
}
// GET: Classes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var #class = await _context.Class.SingleOrDefaultAsync(m => m.ID == id);
if (#class == null)
{
return NotFound();
}
return View(#class);
}
// POST: Classes/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Grade")] Class #class)
{
if (id != #class.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(#class);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ClassExists(#class.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(#class);
}
// GET: Classes/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var #class = await _context.Class
.SingleOrDefaultAsync(m => m.ID == id);
if (#class == null)
{
return NotFound();
}
return View(#class);
}
// POST: Classes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var #class = await _context.Class.SingleOrDefaultAsync(m => m.ID == id);
_context.Class.Remove(#class);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
private bool ClassExists(int id)
{
return _context.Class.Any(e => e.ID == id);
}
}
}
TeachersController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
namespace WebApplication1.Models
{
public class TeachersController : Controller
{
private readonly WebApplication1Context _context;
public TeachersController(WebApplication1Context context)
{
_context = context;
}
// GET: Teachers
public async Task<IActionResult> Index()
{
return View(await _context.Teacher.ToListAsync());
}
// GET: Teachers/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var teacher = await _context.Teacher
.SingleOrDefaultAsync(m => m.ID == id);
if (teacher == null)
{
return NotFound();
}
return View(teacher);
}
// GET: Teachers/Create
public IActionResult Create()
{
return View();
}
// POST: Teachers/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,FirstName,LastName,Birthday")] Teacher teacher)
{
if (ModelState.IsValid)
{
_context.Add(teacher);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(teacher);
}
// GET: Teachers/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var teacher = await _context.Teacher.SingleOrDefaultAsync(m => m.ID == id);
if (teacher == null)
{
return NotFound();
}
return View(teacher);
}
// POST: Teachers/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,FirstName,LastName,Birthday")] Teacher teacher)
{
if (id != teacher.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(teacher);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TeacherExists(teacher.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(teacher);
}
// GET: Teachers/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var teacher = await _context.Teacher
.SingleOrDefaultAsync(m => m.ID == id);
if (teacher == null)
{
return NotFound();
}
return View(teacher);
}
// POST: Teachers/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var teacher = await _context.Teacher.SingleOrDefaultAsync(m => m.ID == id);
_context.Teacher.Remove(teacher);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
private bool TeacherExists(int id)
{
return _context.Teacher.Any(e => e.ID == id);
}
}
}
I know it's been a while since the question has been written, but you should try to Include the object reference you want.
var #class = await _context.Class.Include("Teacher")
.SingleOrDefaultAsync(m => m.ID == id);
Include will get the dependent object and put it back in your Class model.
You can chain the Include directives if you have different referenced objects.
Note : You will have to add :
using Microsoft.EntityFrameworkCore;
on top of your code to allow Include to work.

Dropdown value gets null value

I use breakpoint debug it my ClientsId always come null and display on my payments index always is the first value of my Dropdownlist
Model:
public class Payments
{
[Key]
public int PaymentsId { get; set; }
public int ClientId { get; set; }
public virtual Client Client { get; set; }
}
ViewModel:
public class PaymentsViewModel
{
[Required(ErrorMessage = "Please select a client")]
[Display(Name = "Client")]
public int SelectedClient { get; set; }
public IEnumerable<SelectListItem> Client { get; set; }
}
GET CONTROLLER:
public ActionResult Create(Payments model)
{
var liste= new PaymentsViewModel
{
Clients = new SelectList(db.ClientList, "ClientId", "ClientName")
};
return View(liste);
}
POST CONTROLLER:
public ActionResult Create([Bind(Include = "....")] PaymentsViewModel model)
{
if (ModelState.IsValid)
{
model.PaymentsCreate();
return RedirectToAction("Index", "Payments");
}
return View(model);
}
CREATE VIEW:
#Html.DropDownListFor(m => m.SelectedClient, Model.Clients, "-Please select-", new { #class = "form-control" })
</div>
</div>
--------------------------------------------UPDATE---------------------------------------------------
EDIT CONTROLLER (GET):
public ActionResult Edit(int? id, PaymentsViewModel model)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Payments payments = db.PaymentsList.Find(id);
if (payments == null)
{
return HttpNotFound();
}
return View();
}
EDIT CONTROLLER (POST)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PaymentsId,Paymentnumber,PaymentDate,Amount,Discount,Reference,Total")] Payments payments)
{
if (ModelState.IsValid)
{
db.Entry(payments).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(payments);
}
You should add a ClientsId initialization from model.SelectedClient at PaymentsCreate functions like: ClientsId = model.SelectedClient. And then you need to add SelectedClient string to properties enumeration at Create (post) method to Bind(Include.... attribute

Asp.net MVC #RenderPage with Data

I have controller
public class NewsController : Controller
{
private SchoolDbContext db = new SchoolDbContext();
//
// GET: /News/
public ActionResult Index()
{
return View(db.News.ToList());
}
//
// GET: /News/Details/5
public ActionResult Details(int id = 0)
{
News news = db.News.Find(id);
if (news == null)
{
return HttpNotFound();
}
return View(news);
}
//
// GET: /News/Create
public ActionResult Create()
{
return View();
}
//
// POST: /News/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(News news)
{
if (ModelState.IsValid)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
string path2 = Path.GetRandomFileName();
fileName = path2 + fileName;
var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
news.Image = fileName;
file.SaveAs(path);
}
db.News.Add(news);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(news);
}
//
// GET: /News/Edit/5
public ActionResult Edit(int id = 0)
{
News news = db.News.Find(id);
if (news == null)
{
return HttpNotFound();
}
return View(news);
}
//
// POST: /News/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(News news)
{
if (ModelState.IsValid)
{
db.Entry(news).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(news);
}
//
// GET: /News/Delete/5
public ActionResult Delete(int id = 0)
{
News news = db.News.Find(id);
if (news == null)
{
return HttpNotFound();
}
return View(news);
}
//
// POST: /News/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
News news = db.News.Find(id);
db.News.Remove(news);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
I have a Model
public class News
{
[Key]
public int newsID { get; set; }
[Required]
public string newsName { get; set; }
[Required]
public string newsDescription { get; set; }
public string Image { get; set; }
}
and a simple view
<div class="grid">
#foreach (var item in Model)
{
<div class="holder_content">
<section class="group1">
<h3>#Html.DisplayFor(modelItem => item.newsName)</h3>
<p class="desc">#Html.DisplayFor(modelItem => item.newsDescription)</p>
<a class="photo_hover3" href="#"><img src="~/Uploads/#Html.DisplayFor(modelItem => item.Image)" width="240" height="214" alt=""></a>
<div class="forbutton">
#Html.ActionLink("სრულად ", "Details", new { id = item.newsID }, new { #class = "button" })
</div>
#{ if (User.Identity.IsAuthenticated)
{
#Html.ActionLink("Edit ", "Edit", new { id = item.newsID })
#Html.ActionLink("Delete", "Delete", new { id = item.newsID })
}
}
</section>
}
I want to display this data in another page, where I have this code
#RenderPage("~/Views/News/Index.cshtml")
but web page goes on runtime error, with null pointer exception on foreach tag
have you any solution with this error? sorry for my english. Hope you understand
Please use the partial view rendering.
Note main thing you have to mention the namespace in the view page
Like : #model YourApplicationName.Models.exampleClassName
and then render the page as partial view.
#Html.Partial("partialViewName", new exampleClassName())
or other wise pass the model which you have denoted as namespace in the Partialview like below
#Html.Partial("partialViewName", #Modle.exampleClassName)
or
#Html.Partial("partialViewName", #Modle)

Cannot convert from 'System.Web.Mvc.FormCollection' to 'MyProject.Models.EditViewModel'

I get two following errors in my ASP.NET MVC 3 project:
Error 1 The best overloaded method match for
'SklepAlfa.Models.ProduktyController.Edytuj(int,
SklepAlfa.Models.ProduktyEdytujViewModel)' has some invalid arguments
Error 2 Argument 2: cannot convert from
'System.Web.Mvc.FormCollection' to
'SklepAlfa.Models.ProduktyEdytujViewModel'
Here is my ProduktyEdytujViewModel.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using SklepAlfa.Models;
using System.Web.Mvc;
namespace SklepAlfa.Models
{
public class ProduktyEdytujViewModel
{
public Produkty Produkt { get; set; }
public int id_produktu { get; set; }
public IEnumerable<Kategorie_produktow> Kategorie { get; set; }
}
}
And here it is used in my controller:
public ActionResult Edytuj(int id) //Edit
{
var model = new ProduktyEdytujViewModel //ProductsEditViewModel
{
Produkt = sklepBaza.PobierzProduktWgId(id), //GetProductById
Kategorie = sklepBaza.PobierzKategorieProduktow() //GetProductCategories
};
return View(model);
}
[HttpPost]
public ActionResult Edytuj(int id, ProduktyEdytujViewModel model)
{
if (!ModelState.IsValid)
{
model.Produkt = sklepBaza.PobierzProduktWgId(id);
model.Kategorie = sklepBaza.PobierzKategorieProduktow();
return View(model);
}
return RedirectToAction("Kategorie");
}
What am I doing wrong? Thank you in advance.
In the post action you can pass just the model object and it will contain the id
[HttpPost]
public ActionResult Edytuj(ProduktyEdytujViewModel model)
{
if (!ModelState.IsValid)
{
model.Produkt = sklepBaza.PobierzProduktWgId(model.id);
model.Kategorie = sklepBaza.PobierzKategorieProduktow();
return View(model);
}
return RedirectToAction("Kategorie");
}

Categories

Resources