Im trying to learn myself C# MVC4 with visual studio 2010.
What i want to do is get the full output of 2 models on 1 view selected on someones username.
So if i go to /Teams/Details/1
I will get all the info from the models players and teams.
Models:
public class Players
{
public int ID { get; set; }
public string Name { get; set; }
public int price { get; set; }
public string coach { get; set; }
public string Team { get; set; }
}
public class Teams
{
public int ID { get; set; }
public string Name { get; set; }
public string coach { get; set; }
}
Controller
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using voetbal.Models;
namespace voetbal.Controllers
{
public class TeamsController : Controller
{
private TeamsDBContext db = new TeamsDBContext();
//
// GET: /Teams/
public ActionResult Index()
{
return View(db.Teams.ToList());
}
//
// GET: /Teams/Details/5
public ActionResult Details(int id = 0)
{
Teams teams = db.Teams.Find(id);
if (teams == null)
{
return HttpNotFound();
}
return View(teams);
}
//
// GET: /Teams/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Teams/Create
[HttpPost]
public ActionResult Create(Teams teams)
{
if (ModelState.IsValid)
{
teams.coach = User.Identity.Name;
db.Teams.Add(teams);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(teams);
}
//
// GET: /Teams/Edit/5
public ActionResult Edit(int id = 0)
{
Teams teams = db.Teams.Find(id);
if (teams == null)
{
return HttpNotFound();
}
return View(teams);
}
//
// POST: /Teams/Edit/5
[HttpPost]
public ActionResult Edit(Teams teams)
{
if (ModelState.IsValid)
{
db.Entry(teams).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(teams);
}
//
// GET: /Teams/Delete/5
public ActionResult Delete(int id = 0)
{
Teams teams = db.Teams.Find(id);
if (teams == null)
{
return HttpNotFound();
}
return View(teams);
}
//
// POST: /Teams/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Teams teams = db.Teams.Find(id);
db.Teams.Remove(teams);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
I have absolutely how to get this done, i have tried a viewmodel class but i have no idea how to get this information on someones coach name.
Im looking forward to your reply.
There are a lot of ways to skin this cat, but one thing you have to first see is that you’re not sending back even one instance of both models. If you examine the code for the
Detailsaction:clearly all we are sending back is one instance of the
Teamsmodel. So, let’s examine an option that we have. Consider the following code:now in the View we can set our model to this (note you will need to fully qualify
TeamsandPlayersin the @model declaration):and from there we can do stuff like:
or: