多对多的MVC 5型号先写加盟表 [英] Many to many MVC 5 Model first write to join table

查看:191
本文介绍了多对多的MVC 5型号先写加盟表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个局部的工作code。与许多人的球队和球员(和结​​表TeamPlayers)之间有很多关系。下拉的球队和球员方菜单没有work.Though数据存储在数据库(球员和团队表)而不是结表TeamPlayers。

我想在我的现役球员和球队目前来看可能性相连,又名,我在路口表保存当前TeamId到TeamId(和PlayerId到PlayerId)。最后插入一步.... i'm完全卡住....
感谢所有样的帮助。在看到我下面code,并要求更多,如果必要的。提前致谢!
/ THA猪

示范m2mContext.cs

 公共类m2mContext:的DbContext
    {
        //你可以添加自定义code到这个文件。更改将不会被覆盖。
        //
        //如果你想Entity Framework的下跌并重新生成数据库
        //自动每当你改变你的模型模式,请用数据迁移。
        //欲了解更多信息,请参阅文档:
        // http://msdn.microsoft.com/en-us/data/jj591621.aspx        公共m2mContext():基地(NAME = m2mContext)
        {
        }        公共System.Data.Entity.DbSet< m2m.Models.Team>小组{搞定;组; }        公共System.Data.Entity.DbSet< m2m.Models.Player>播放器{搞定;组; }    }

示范Team.cs

 命名空间m2m.Models
{
    公共类团队
    {
        公众诠释TeamId {搞定;组; }
        [需要]
        公共字符串TeamName {搞定;组; }        公众诠释PlayerId {搞定;组; }
        公共虚拟的ICollection<玩家GT;播放器{搞定;组; } //这是新的    }
}

示范Player.cs

 命名空间m2m.Models
{
    公共类播放器
    {
        公众诠释PlayerId {搞定;组; }
        公共字符串PlayerName {搞定;组; }
        公众诠释TeamId {搞定;组; }        //公共虚拟团队团队{搞定;组; } //这是新的        公共虚拟的ICollection<团队及GT;小组{搞定;组; }
    }
}

控制器TeamController.cs

 命名空间m2m.Controllers
{
    公共类TeamController:控制器
    {
        私人m2mContext DB =新m2mContext();        // GET:团队
        公众的ActionResult指数()
        {
            返回查看(db.Teams.ToList());
        }        // GET:团队/详细资料/ 5
        公众的ActionResult详细信息(INT?ID)
        {
            如果(ID == NULL)
            {
                返回新的HTTPStatus codeResult(的HTTPStatus code.BadRequest);
            }
            团队团队= db.Teams.Find(ID);
            如果(团队== NULL)
            {
                返回HttpNotFound();
            }
            返回查看(队);
        }        // GET:团队/创建
        公众的ActionResult的Create()
        {
            返回查看();
        }        // POST:团队/创建
        //从overposting攻击保护,请启用要绑定到特定的属性,
        //更多详情请参阅http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        公众的ActionResult创建([绑定(包括=TeamId,TeamName,PlayerId),队伍的团队)
        {
            如果(ModelState.IsValid)
            {
                db.Teams.Add(队);
                db.SaveChanges();
                返回RedirectToAction(「指数」);
            }            返回查看(队);
        }

控制器PlayerController.cs

 命名空间m2m.Controllers
{
    公共类的PlayerController:控制器
    {
        私人m2mContext DB =新m2mContext();        //获取:玩家
        公众的ActionResult指数()
        {
            返回查看(db.Players.ToList());
        }        // GET:播放器/详细资料/ 5
        公众的ActionResult详细信息(INT?ID)
        {
            如果(ID == NULL)
            {
                返回新的HTTPStatus codeResult(的HTTPStatus code.BadRequest);
            }
            Player播放器= db.Players.Find(ID);
            如果(球员== NULL)
            {
                返回HttpNotFound();
            }
            返回查看(播放器);
        }        // GET:播放器/创建
        公众的ActionResult的Create()
        {
            返回查看();
        }        // POST:播放器/创建
        //从overposting攻击保护,请启用要绑定到特定的属性,
        //更多详情请参阅http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        公众的ActionResult创建([绑定(包括=PlayerId,PlayerName,TeamId)] Player播放器)
        {
            如果(ModelState.IsValid)
            {
                db.Players.Add(播放器);
                db.SaveChanges();
                返回RedirectToAction(「指数」);
            }            返回查看(播放器);
        }

查看团队

创建

  @using(Html.BeginForm())
{
    @ Html.AntiForgeryToken()    < D​​IV CLASS =形横>
        < H4>团队及LT; / H4>
        <小时/>
        @ Html.ValidationSummary(真,新{@class =TEXT-危险})
        < D​​IV CLASS =表单组>
            @ Html.LabelFor(型号=> model.TeamName,htmlAttributes:新{@class =控制标签COL-MD-2})
            < D​​IV CLASS =COL-MD-10>
                @ Html.EditorFor(型号=> model.TeamName,新{htmlAttributes = {新@class =表格控}})
                @ Html.ValidationMessageFor(型号=> model.TeamName,新{@class =TEXT-危险})
            < / DIV>
        < / DIV>        < D​​IV CLASS =表单组>
            @ Html.LabelFor(型号=> model.PlayerId,htmlAttributes:新{@class =控制标签COL-MD-2})
            < D​​IV CLASS =COL-MD-10>
                @ Html.EditorFor(型号=> model.PlayerId,新{htmlAttributes = {新@class =表格控}})
                @ Html.ValidationMessageFor(型号=> model.PlayerId,新{@class =TEXT-危险})
            < / DIV>
        < / DIV>        < D​​IV CLASS =表单组>
            < D​​IV CLASS =COL-MD-偏移2 COL-MD-10>
                <输入类型=提交值=创建类=BTN BTN-默认的/>
            < / DIV>
        < / DIV>
    < / DIV>
}

查看播放器

创建

  @using(Html.BeginForm())
{
    @ Html.AntiForgeryToken()    < D​​IV CLASS =形横>
        < H4>播放器和LT; / H4>
        <小时/>
        @ Html.ValidationSummary(真,新{@class =TEXT-危险})
        < D​​IV CLASS =表单组>
            @ Html.LabelFor(型号=> model.PlayerName,htmlAttributes:新{@class =控制标签COL-MD-2})
            < D​​IV CLASS =COL-MD-10>
                @ Html.EditorFor(型号=> model.PlayerName,新{htmlAttributes = {新@class =表格控}})
                @ Html.ValidationMessageFor(型号=> model.PlayerName,新{@class =TEXT-危险})
            < / DIV>
        < / DIV>        < D​​IV CLASS =表单组>
            @ Html.LabelFor(型号=> model.TeamId,htmlAttributes:新{@class =控制标签COL-MD-2})
            < D​​IV CLASS =COL-MD-10>
                @ Html.EditorFor(型号=> model.TeamId,新{htmlAttributes = {新@class =表格控}})
                @ Html.ValidationMessageFor(型号=> model.TeamId,新{@class =TEXT-危险})
            < / DIV>
        < / DIV>        < D​​IV CLASS =表单组>
            < D​​IV CLASS =COL-MD-偏移2 COL-MD-10>
                <输入类型=提交值=创建类=BTN BTN-默认的/>
            < / DIV>
        < / DIV>
    < / DIV>
}


解决方案

问题是你发布到属性 PlayerId / TeamId 。这是一个如此M2M这些领域没有做任何事情。你必须提供多选择将最终发布ID的列表。然后,您可以使用此发布ID列表来查找从数据库中玩家/团队,并将它们添加到各自的集合。

I have a "partial" working code with many to many relationship between Teams and Players (and junction table TeamPlayers). The drop down menu on Team and Player side does not work.Though data is stored in db (Player and Team tables)BUT NOT to junction table TeamPlayers.

I want to have the possibility in my view for current players and current teams to be connected, aka, save a current TeamId to TeamId in my junction table (and PlayerId to PlayerId). The last insert step is....i´m totally stuck.... Grateful for all kind of help. the See my code below, and ask for more if necessary. Thanks in advance! /Tha Pig

Model 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; }

    }

Model 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

    }
}

Model 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; }
    }
}

Controller 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);
        }

Controller 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);
        }

View Team

Create

@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>
}

View Player

Create

@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>
}

解决方案

The problem is your posting to properties PlayerId/TeamId. This is a M2M so these fields don't do anything. You have to provide a multi-select that will end up posting a list of ids. Then you can use this posted list of ids to lookup the players/teams from the database and add them to their respective collections.

这篇关于多对多的MVC 5型号先写加盟表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆