.net mvc视图中的一对多关系

时间:2015-02-26 14:13:56

标签: c# asp.net-mvc linq

查看型号:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
    {
    public class Employee
    {
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string phone { get; set; }

        [Required]
        [EmailAddress]
        public string email { get; set; }
        }
    }

查看:

@model WebApplication1.Models.Employee

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Employee</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

         <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name, "", 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>
}

<div>
    @Html.ActionLink("Back to List", "Index")
 </div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

如果用户想插入多个电话号码和电子邮件地址,我想同时从视图中删除多个电话号码和电子邮件地址。

直到工作正常但如何实现电话号码和电子邮件地址?

感谢。

1 个答案:

答案 0 :(得分:0)

您需要将手机和电子邮件分解为自己的类,然后在它们和Employee之间添加一对多关系:

public class Phone
{
    public string Phone { get; set; }
}

public class Email
{
    public string Email { get; set; }
}

public class Employee
{
    ...

    public virtual ICollection<Phone> Phones { get; set; }

    public virtual ICollection<Email> Emails { get; set; }
}