vista tutorial paso net mvc modelo form filtros filtro controlador busqueda buscador asp c# entity-framework asp.net-mvc-5 many-to-many

paso - mvc c# tutorial



Muchos a muchos modelo MVC 5 primero escriben para unirse a la tabla (2)

El problema es publicar en las propiedades PlayerId / TeamId . Este es un M2M por lo que estos campos no hacen nada. Debe proporcionar una selección múltiple que terminará publicando una lista de identificadores. Luego puede usar esta lista publicada de identificadores para buscar los jugadores / equipos de la base de datos y agregarlos a sus respectivas colecciones.

Tengo un código de trabajo "parcial" con muchas a muchas relaciones entre equipos y jugadores (y la tabla de unión TeamPlayers). El menú desplegable del equipo y del lado del jugador no funciona. Aunque los datos se almacenan en db (tablas de jugadores y equipos) PERO NO en la tabla de uniones TeamPlayers.

Quiero tener la posibilidad, en mi opinión, de que los jugadores actuales y los equipos actuales estén conectados, es decir, guardar un ID de equipo actual en ID de equipo en mi mesa de unión (y PlayerId a PlayerId). El último paso de inserción es .... estoy totalmente atascado ... Agradecido por todo tipo de ayuda. Ver mi código a continuación, y pedir más si es necesario. ¡Gracias por adelantado! / Tha Pig

Modelo m2mContext.cs

public class m2mContext : DbContext { // You can add custom code to this file. Changes will not be overwritten. // // If you want Entity Framework to drop and regenerate your database // automatically whenever you change your model schema, please use data migrations. // For more information refer to the documentation: // http://msdn.microsoft.com/en-us/data/jj591621.aspx public m2mContext() : base("name=m2mContext") { } public System.Data.Entity.DbSet<m2m.Models.Team> Teams { get; set; } public System.Data.Entity.DbSet<m2m.Models.Player> Players { get; set; } }

Modelo Team.cs

namespace m2m.Models { public class Team { public int TeamId { get; set; } [Required] public string TeamName { get; set; } public int PlayerId { get; set; } public virtual ICollection<Player> Players { get; set; } // This is new } }

Modelo Player.cs

namespace m2m.Models { public class Player { public int PlayerId { get; set; } public string PlayerName { get; set; } public int TeamId { get; set; } // public virtual Team Team { get; set; } // This is new public virtual ICollection<Team> Teams { get; set; } } }

Controlador TeamController.cs

namespace m2m.Controllers { public class TeamController : Controller { private m2mContext db = new m2mContext(); // GET: Team public ActionResult Index() { return View(db.Teams.ToList()); } // GET: Team/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Team team = db.Teams.Find(id); if (team == null) { return HttpNotFound(); } return View(team); } // GET: Team/Create public ActionResult Create() { return View(); } // POST: Team/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([Bind(Include = "TeamId,TeamName,PlayerId")] Team team) { if (ModelState.IsValid) { db.Teams.Add(team); db.SaveChanges(); return RedirectToAction("Index"); } return View(team); }

Controlador PlayerController.cs

namespace m2m.Controllers { public class PlayerController : Controller { private m2mContext db = new m2mContext(); // GET: Player public ActionResult Index() { return View(db.Players.ToList()); } // GET: Player/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Player player = db.Players.Find(id); if (player == null) { return HttpNotFound(); } return View(player); } // GET: Player/Create public ActionResult Create() { return View(); } // POST: Player/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([Bind(Include = "PlayerId,PlayerName,TeamId")] Player player) { if (ModelState.IsValid) { db.Players.Add(player); db.SaveChanges(); return RedirectToAction("Index"); } return View(player); }

Ver equipo

Crear

@using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Team</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.TeamName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.TeamName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.TeamName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.PlayerId, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.PlayerId, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.PlayerId, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> }

Ver jugador

Crear

@using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Player</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.PlayerName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.PlayerName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.PlayerName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.TeamId, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.TeamId, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.TeamId, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> }


No puedo hacer ningún comentario debido a mi representante, así que publicaré una posible respuesta.

Agregaría TeamPlayers al modelo, agregaré un método a los jugadores y / o al controlador del equipo para agregarlos al TeamPlayer.

public System.Data.Entity.DbSet<m2m.Models.TeamPlayer> TeamPlayer{ get; set; }

En controlador (es)

public ActionResult AddtoTeam(int? Teamid) public ActionResult AddPlayer(int? Playerid)

No del todo seguro de que esto es lo que quieres.