Cannot show products (courses) in my MVC project - c#

i need help with my MVC Project.
My page will shown avaible Courses so i need to show Courses on page
my code looks like this but doesnt work
i try to show properties for Courses from CourseViewModel in
public ActionResult Index()
{
var viewModel = new List<CourseViewModel>();
CourseViewModel Courses = new CourseViewModel();
Courses = new CourseViewModel();
return View(viewModel);
}
would be so glad if someone could help me..

Assuming your class looks like this based on your comments
public class CourseViewModel {
public int CourseId { get; set; }
public string CourseName { get; set; }
public string CoursePlace { get; set; }
public string CourseLevel { get; set; }
public string CourseDate { get; set; }
public string CourseDescription { get; set; }
public string CourseBookUrl { get; set; }
}
You populate your list to pass as the viewmodel for your view
public ActionResult Index() {
var viewModel = new List<CourseViewModel>();
//Either get the viewmodels from a data source or add them yourself
var course = new CourseViewModel() {
CourseId = 1,
CourseName = "Maths 101",
CoursePlace = "Some class room",
CourseLevel = "1",
CourseDate = "",
//..populate other properties
};
viewModel.Add(course);
//repeat to add more courses
return View(viewModel);
}
In your view you specify what type the view model is
#model List<CourseViewModel>
and you can traverse the model and display the details.
#foreach (var course in Model) {
<div>#course.CourseName</div>
<!--other details you want to display-->
}

Related

Load data from many to many related tables in one view asp.net

I'm new to asp.net and may be missing some simple solution. So basically i've got two tables Movie and Actor here are their models:
public class Movie
{
public Movie()
{
this.Actors = new HashSet<Actor>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Genre { get; set; }
[Required]
public DateTime ReleaseDate { get; set; }
[Required]
public DateTime AddDate { get; set; }
public virtual ICollection<Actor> Actors { get; set; }
}
public class Actor
{
public Actor()
{
this.Movies = new HashSet<Movie>();
}
public int id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Movie> Movies { get; set; }
public DateTime BirthDate { get; set; }
}
I'm trying to load movie details and the list of actors from the movie using ViewModel:
public class MovieDetailsViewModel
{
public Movie Movie { get; set; }
public Actor Actor { get; set; }
}
And the controller for it is here:
private ApplicationDbContext _context;
public MoviesController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
public ActionResult Index()
{
var movie = _context.Movies.ToList();
return View(movie);
}
public ActionResult Details(int id)
{
var movie = _context.Movies.SingleOrDefault(m => m.Id == id);
var actor = _context.Actors.SingleOrDefault(a => a.id == id);
var viewModel = new MovieDetailsViewModel
{
Movie = movie,
Actor = actor
};
if (movie == null)
return HttpNotFound();
return View(viewModel);
}
Action Details is the one that needs to be loading the data that I need.
View looks something like this:
#model Movie_Rentals.ViewModels.MovieDetailsViewModel
#{
ViewBag.Title = Model.Movie.Name;
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#Model.Movie.Name</h2>
<ul>
<li>Genre: #Model.Movie.Genre</li>
<li>Release date: #Model.Movie.ReleaseDate.ToShortDateString()</li>
<li>Add date: #Model.Movie.AddDate.ToShortDateString()</li>
<li>Actors:#Model.Movie.Actors</li>
</ul>
And it displays Actors:System.Collections.Generic.HashSet`1[Movie_Rentals.Models.Actor] which I suppose it should, but I can't mannge to find a solution on how to make it to display the actual list of actors. Does anyone have any idea on my issue, I would appreciate any help.
P.S. I'm not a native english speaker, so sorry if my english is bad.
in your view you could try:
<li>Actors: #string.Join("," Model.Movie.Actors.Select(a => a.Name).ToList())</li>
In this way, you will show a list of actors' names associated with the movie you added to your view model.
But I would suggest you refactor your view model to include a List of actors' names, so you would remove the logic from your view. After that, your view should look like:
public class MovieDetailsViewModel
{
public Movie Movie { get; set; }
public List<string> ActorsNames { get; set; }
}
In your controller you should do:
public ActionResult Details(int id)
{
var movie = _context.Movies.SingleOrDefault(m => m.Id == id);
var viewModel = new MovieDetailsViewModel
{
Movie = movie,
ActorsNames = string.Join(",", movie.Actors.Select(a => a.Name).ToList())
};
if (movie == null)
return HttpNotFound();
return View(viewModel);
}
As you can see, I have removed the code where you get a single actor from the Actors DbSet because it isn't useful. Indeed, you want the full list of all actors that have appeared in the movie you get from the Movies DbSet, not just an actor that has the same id of the movie of which you have to load the details.
Also, be sure to have activated lazy loading to get the collection of actors associated with the movie, otherwise, you will get an empty collection.
Let me know if my suggestions will be useful.
You need to load the Movie with all Actors using
_context.Movies.Include(x => x.Actors).SingleOrDefault(m => m.Id == id);
Then in the View
#foreach (var x in Model.Movie.Actors)
{<li>x.Name</li>}
To allow for the Actors field to show, you can handle this in a few ways. The easiest solution would be to add a property that parses the Actors collection into a string. You could also write code directly into the View to loop over each actor in the collection.
Example:
public class Movie
{
public Movie()
{
this.Actors = new HashSet<Actor>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Genre { get; set; }
[Required]
public DateTime ReleaseDate { get; set; }
[Required]
public DateTime AddDate { get; set; }
public virtual ICollection<Actor> Actors { get; set; }
public string ActorsToString
{
get
{
string _resultSet = "";
if (Actors != null && Actors.Count > 0)
{
foreach (Actor _actor in Actors)
{
_resultSet += $"{_actor.Name}, ";
}
}
return _resultSet;
}
}
}

C# Editing ViewModel

I have my ViewModel, and I have my controller to display from the ViewModel correctly, however I'm not sure how I would make the ViewModel editable, as to send the edited data back to the Model. I only want to edit the OrderArchiveViewModel, not the details
ViewModel;
public class OrderArchiveViewModel
{
public int OrderId { get; set; }
public System.DateTime OrderDate { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public decimal Total { get; set; }
public bool HasBeenShipped { get; set; }
public List<OrderDetailArchive> Details { get; set; }
}
public class OrderDetailArchive
{
public string Title { get; set; }
public string Colour { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
}
Controller;
[Authorize(Roles = "Administrator")]
public ActionResult Index()
{
List<T_shirt_Company_v3.ViewModels.OrderArchiveViewModel> list = (from o in new TshirtStoreDB().Orders
.OrderBy(o => o.OrderDate)
.Select(o => new OrderArchiveViewModel()
{
OrderId = o.OrderId,
Address = o.Address,
FirstName = o.FirstName,
LastName = o.LastName,
City = o.City,
OrderDate = o.OrderDate,
PostalCode = o.PostalCode,
Total = o.Total,
HasBeenShipped = o.HasBeenShipped,
Details = (from d in o.OrderDetails
select new OrderDetailArchive
{
Colour = d.Product.Colour,
Quantity = d.Quantity,
Title = d.Product.Title,
UnitPrice = d.UnitPrice
}).ToList()
}).ToList()select o).ToList();
ViewBag.ShippedMessage = list.Where(w => w.HasBeenShipped).Any() ? "Order has been shipped" : "Order is being processed";
return View(list);
}
I can suggest you to make an another two actions.
public ActionResult Edit(int id)
where you will get the Order by it's Id, map to ViewModel and pass it to the view where you will have textboxes for editing. Create another one Action for accepting post request with updated model:
[HttpPost]
public ActionResult Edit(OrderArchiveViewModel model)
When the the edit page is submitted you will have a updated model with the new data, then find your model in database by Id and update the properties.
Can u send the code of your View to get more clarification?
The already given answer could be done by redirect to a page for editing purpose.
Do you want to show the Editing fields above the Grid?
For this purpose, you can add New ViewModel like
public class NewViewModel
{
public OrderArchiveViewModel OrderArchiveViewModel { get; set; }
public List<OrderArchiveViewModel> OrderArchiveViewModelList { get; set; }
}
And you can send data using this NewViewModel to View containing both editable OrderArchiveViewModel depending on the Id and also the List of OrderArchiveViewModel by assigning the list present in Index() action.

Using the selected item from DropDownList in MVC

I'm trying to use the user selected item from the DropDownList to create a new entry in my Database table that is related/linked?(Not sure of correct wording for this) to the DropDownList item.
Here are my Models
public class TaskInstance
{
public int Id { get; set; }
public DateTime DueDate { get; set; }
public int HowMany { get; set; }
public Task TaskId { get; set; }
public virtual Task Task { get; set; }
}
public class TaskInstanceViewModel
{
[DataType(DataType.DateTime)]
public DateTime DueDate { get; set; }
public int HowMany { get; set; }
public IEnumerable<SelectListItem> TaskList { get; set; }
public virtual ICollection<Task> Task { get; set; }
}
public class Task
{
public Task()
{
TaskInstance = new HashSet<TaskInstance>();
}
public int Id { get; set;}
public string Name { get; set; }
public string Unit { get; set; }
public virtual ICollection<TaskInstance> TaskInstance { get; set; }
}
Controllers
public ActionResult Create()
{
var model = new TaskInstanceViewModel();
model.TaskList = db.Task.ToList().Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
}).ToList();
return View(model);
}
// POST: TaskInstances/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(TaskInstanceViewModel model)
{
if (ModelState.IsValid)
{
var taskinstance = new TaskInstance { DueDate = model.DueDate };
db.TaskInstance.Add(taskinstance);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
View - This is the only one I need to show I think, the others are just fields
#Html.DropDownListFor(x => Model.TaskList, (SelectList)Model.Task)
On the controller where it says var taskinstance = new TaskInstance { DueDate = model.DueDate }; Would be where i need to use the selected item from the User but I have no idea how to get it, i've looked through a lot of posts but most of them is just how to make the DropDownList in the first place but not how to use it(Being a link to another table) with a new database entry.
I'd also like to mention that I am still new to MVC so feel free to point out if im going about this the wrong way
Add a new property of type int to store the selected task from the dropdown. Remember view models are specific to the view.so keep only those properties you absolutely need in the view, in your view model.
public class TaskInstanceViewModel
{
public DateTime DueDate { get; set; }
public int HowMany { get; set; }
public IEnumerable<SelectListItem> TaskList { get; set; }
public int SelectedTask {set;get;} // new property
}
And in your view
#model TaskInstanceViewModel
#using(Html.BeginForm())
{
<label> How many</label>
#Html.TextBoxFor(s=>s.HowMany)
<label>Due date</label>
#Html.TextBoxFor(s=>s.DueDate)
<label>Task</label>
#Html.DropDownListFor(s => s.SelectedTask, Model.TaskList)
<input type="submit" />
}
And in your HttpPost action, you can use the SelectedTask property value which will have the Id of the task selected
[HttpPost]
public ActionResult Create(TaskInstanceViewModel model)
{
if (ModelState.IsValid)
{
var taskinstance = new TaskInstance { DueDate = model.DueDate ,
TaskId=model.SelectedTask };
db.TaskInstance.Add(taskinstance);
db.SaveChanges();
return RedirectToAction("Index");
}
model.TaskList = db.Task.ToList().Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
}).ToList();
return View(model);
}
It seems to me that you need you point to a property that represents the selected item in the dropdown. The dropdown items is IEnumerable<SelectListItem> why isn't the selected item a property of type SelectListItem?
Add a property to your view model:
public class TaskInstanceViewModel
{
[DataType(DataType.DateTime)]
public DateTime DueDate { get; set; }
public int HowMany { get; set; }
public IEnumerable<SelectListItem> TaskList { get; set; }
public virtual ICollection<Task> Task { get; set; }
//add this property:
public SelectListItem SelectedItem { get; set; }
}
And modify the view:
#Html.DropDownListFor(x => Model.TaskList, Model.SelectedItem )

MVC Dropdown using ViewModels without Magic String

I am trying to get a drop-down from a database to work. I did not get too far. I am trying to do it using viewModel and not use Magic String. I have a feeling I am not too far off. Could some please take a look and see what I am missing or doing wrong?
I am getting a compiling error at this line in the controller: viewModel.Courts = CourtList,
I am pretty sure it is wrong but I am running of ideas on how to do this.
Domain Models:
public class Parent
{
public int ParentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Court Court { get; set; }
//public IEnumerable<SelectListItem> Courts { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Court
{
public int CourtId { get; set; }
public string CourtName { get; set; }
public virtual ICollection<Parent> Parents { get; set; }
}
View Model:
public class ParentVM
{
public int ParentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
//public int CourtId { get; set; }
//public string CourtName { get; set; }
public virtual Court Court { get; set; }
//public virtual IEnumerable<Court> CourtList { get; set; }
public IEnumerable<SelectListItem> Courts { get; set; }
public IList<ChildVM> Children { get; set; }
}
Controller:
// GET: Parents/Create
public ActionResult Create()
{
IEnumerable<SelectListItem> CourtList = db.Courts.ToList().Select(x => new SelectListItem
{
Value = x.CourtId.ToString(),
Text = x.CourtName,
});
//ViewBag.CourtList = new SelectList(db.Courts, "CourtId", "CourtName");
ParentVM viewModel = new ParentVM()
{
Children = new List<ChildVM>()
{
new ChildVM(){Name="", DOB="", Address=""},
//new ChildVM(){Name="2", DOB="2", Address="222"},
//new ChildVM(){Name="3", DOB="3", Address="3"},
},
viewModel.Courts = CourtList,
};
return View(viewModel);
}
// POST: Parents/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 ActionResult Create(ParentVM viewModel)
{
if (ModelState.IsValid)
{
var parent = new Parent()
{
FirstName = viewModel.FirstName,
LastName = viewModel.LastName
};
db.Parents.Add(parent);
foreach (ChildVM item in viewModel.Children)
{
var child = new Child()
{
Name = item.Name,
DOB = item.DOB,
Address = item.Address
};
db.Childs.Add(child);
}
//Parent parent = new Parent();
//var employee = AutoMapper.Mapper.Map<Parent, ParentVM>(parent);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}
View:
#Html.DropDownList("Courts", (IEnumerable<SelectListItem>)Model.Courts)
Your trying to bind you dropdownlist to property Courts which is IEnumerable<SelectListItem>. A <select> posts back a value type (the value of the selected item) which cannot be bound to a collection. You need an additional property to bind to (or you could bind to Court.CourtId, but the CourtName property of Court wont be bound on postback.
View model
public class ParentVM
{
public int ParentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Required]
public int? SelectedCourt { get; set; } // bind the dropdown to this
public SelectList CourtList { get; set; }
public IList<ChildVM> Children { get; set; }
}
Controller
public ActionResult Create()
{
ParentVM model = new ParentVM()
{
Children = new List<ChildVM>() .....,
CourtList = new SelectList(db.Courts, "CourtId", "CourtName"),
SelectCourt = // set a value here if you want a specific option to be selected
});
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ParentVM model)
{
if (ModelState.IsValid)
{
Court court = db.Courts.Find(model.SelectedCourt) // get the Court based on `SelectedCourt`
var parent = new Parent()
{
FirstName = model.FirstName,
LastName = model.LastName,
Court = court
};
db.Parents.Add(parent);
foreach (ChildVM item in viewModel.Children)
{
....
db.Childs.Add(child);
}
db.SaveChanges();
return RedirectToAction("Index");
}
model.CourtList = new SelectList(db.Courts, "CourtId", "CourtName"); // reassign select list
return View(model);
}
View
#Html.DropDownListFor(m => m.SelectedCourt, Model.CourtList, "--Please select--")
If the value of SelectedCourt matches the value of one of the options, it will be selected when the page is rendered, otherwise the first (label) option will be selected. When you post back, the value of SelectedCourt will be the value of the selected option

MVC4 C# Populating data in a viewmodel from database

I have a viewmodel which needs data from two models person and address:
Models:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int Gender { get; set; }
}
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public int Zip { get; set; }
public int PersonId {get; set; }
}
The Viewmodel is as such
public class PersonAddViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Street { get; set; }
}
I have tried several ways to get data into the viewmodel and pass it to the view. There will be multiple records returned to display.
My latest method is populating the view model as such:
private AppContexts db = new AppContexts();
public ActionResult ListPeople()
{
var model = new PersonAddViewModel();
var people = db.Persons;
foreach(Person p in people)
{
Address address = db.Addresses.SingleOrDefault(a => a.PersonId == p.Id)
model.Id = p.Id;
model.Name = p.Name;
model.Street = address.Street;
}
return View(model.ToList());
}
I get an error on the Address address = db... line of "EntityCommandExecutionException was unhandled by user code.
How can you populate a view model with multiple records and pass to a view?
Final Solution:
private AppContexts db = new AppContexts();
private AppContexts dbt = new AppContexts();
public ActionResult ListPeople()
{
List<PersonAddViewModel> list = new List<PersonAddViewModel>();
var people = db.Persons;
foreach(Person p in people)
{
PersonAddViewModel model = new PersonAddViewModel();
Address address = dbt.Addresses.SingleOrDefault(a => a.PersonId == p.Id)
model.Id = p.Id;
model.Name = p.Name;
model.Street = address.Street;
}
return View(list);
}
First, EntityCommandExecutionException errors indicates an error in the definition of your entity context, or the entities themselves. This is throwing an exception because it's found the database to be different from the way you told it that it should be. You need to figure out that problem.
Second, regarding the proper way to do this, the code you've shown should work if your context were correctly configured. But, a better way would be to use Navigational properties, so long as you want to get all related records and not specify other Where clause parameters. A navigational property might look like this:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int Gender { get; set; }
public virtual Address Address { get; set; }
// or possibly, if you want more than one address per person
public virtual ICollection<Address> Addresses { get; set; }
}
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public int Zip { get; set; }
public int PersonId { get; set; }
public virtual Person Person { get; set; }
}
Then you would simply say:
public ActionResult ListPeople()
{
var model = (from p in db.Persons // .Includes("Addresses") here?
select new PersonAddViewModel() {
Id = p.Id,
Name = p.Name,
Street = p.Address.Street,
// or if collection
Street2 = p.Addresses.Select(a => a.Street).FirstOrDefault()
});
return View(model.ToList());
}
For displaying lists of objects, you could use a generic view model that has a generic list:
public class GenericViewModel<T>
{
public List<T> Results { get; set; }
public GenericViewModel()
{
this.Results = new List<T>();
}
}
Have a controller action that returns, say all people from your database:
[HttpGet]
public ActionResult GetAllPeople(GenericViewModel<People> viewModel)
{
var query = (from x in db.People select x); // Select all people
viewModel.Results = query.ToList();
return View("_MyView", viewModel);
}
Then make your view strongly typed, taking in your generic view model:
#model NameSpace.ViewModels.GenericViewModel<NameSpace.Models.People>

Categories

Resources