通过选择下拉列表将数据插入数据库

时间:2016-08-30 17:31:19

标签: asp.net-mvc entity-framework linq

我正在尝试从学生注册表单中将数据插入数据库。进入学生表的数据和表单数据的某些部分进入Applied表。输入STUDENT表中的数据和从APPLIED表中的下拉列表中选择的课程。我无法从选定的课程中获取CourseID。

问题在于控制器中的代码:

var apply = new Applied { StudentID = application.StudentID, CourseID = application.CourseID  }; 

在调试模式下,它没有在CourseID中显示任何数据。

以下是我的代码。

视图模型:

public class Application2
{
    public int StudentID { get; set; }        //PK

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime DateOfBirth { get; set; }

    public string Address { get; set; }

    public double PhoneNumber { get; set; }

    public string Email { get; set; }

    public DateTime AppliedDate { get; set; }

    public int AppliedID { get; set; }      //PK

    public int CourseID { get; set; }       //FK

}

控制器:

public ActionResult Index()
{
    return View();
}

public ActionResult DepartmentList()
{
    var departments = db.Departments.OrderBy(x => x.DpName).ToList();

    if (HttpContext.Request.IsAjaxRequest())
    {
        return Json(new SelectList(
                    departments,
                    "DepartmentID",
                    "DpName"), JsonRequestBehavior.AllowGet
                    );
    }

    return View(departments);
}

public ActionResult CourseList(int DepartmentID)
{
    var courses = db.Courses.Where(x => x.DepartmentID == DepartmentID).ToList();

    if (HttpContext.Request.IsAjaxRequest())
        return Json(new SelectList(courses, "CourseID", "CourseName"), JsonRequestBehavior.AllowGet);

    return View(courses);
}


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Application2 application)
{
    var student = new Student { StudentID = application.StudentID, FirstName = application.FirstName, LastName = application.LastName, DateOfBirth = application.DateOfBirth, Address = application.Address, PhoneNumber = application.PhoneNumber, Email = application.Email, AppliedDate = application.AppliedDate };

    var apply = new Applied { StudentID = application.StudentID, CourseID = application.CourseID  }; 

    if (ModelState.IsValid)
    {
        using (var db = new RegistrarsContext())


            db.Students.Add(student);

            db.Applied.Add(apply).ApplicationStatus = Status.Applied;

            db.SaveChanges();
            return RedirectToAction("Index", "Student");
    }

    return  View();
}

以下是VIEW:

@model StudentsRegistration.ViewModels.Application2

@{
    ViewBag.Title = "Student Appication";
    Layout = "~/Views/Shared/_Layout2.cshtml";
}
<h2>Student Application Form</h2>

@using (Html.BeginForm("Create", "Application2", FormMethod.Post))
{
    @Html.AntiForgeryToken()

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

        <div class="form-group">
            @Html.LabelFor(model => model.StudentID, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StudentID, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StudentID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName)
                @Html.ValidationMessageFor(model => model.StudentID)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName)
                @Html.ValidationMessageFor(model => model.LastName)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DateOfBirth)
                @Html.ValidationMessageFor(model => model.DateOfBirth)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address)
                @Html.ValidationMessageFor(model => model.Address)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PhoneNumber)
                @Html.ValidationMessageFor(model => model.PhoneNumber)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email)
                @Html.ValidationMessageFor(model => model.Email)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AppliedDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AppliedDate)
                @Html.ValidationMessageFor(model => model.AppliedDate)
            </div>
        </div>
        <br>
        <br>
        <div class="form-group">

            <label for="Departments">Departments</label>
            <select id="Departments" name="Departments"></select>
            <br /><br />

        </div>

        <div class="form-group">

            <label for="Courses">Courses</label>
            <select id="Courses" name="Courses"></select>

        </div>

        @section scripts {
            <script type="text/javascript">
        $(function () {
            $.getJSON("/Application2/Departments/List", function (data) {
                var items = "<option>---------------------</option>";
                $.each(data, function (i, country) {
                    items += "<option value='" + country.Value + "'>" + country.Text + "</option>";
                });
                $("#Departments").html(items);
            });

            $("#Departments").change(function () {
                $.getJSON("@Url.Action("CourseList", "Application2")?DepartmentID=" + $("#Departments").val(), function (data) {
                    var items = "<option>---------------------</option>";
                    $.each(data, function (i, state) {
                        items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                    });
                    $("#Courses").html(items);
                });
            });
        });
            </script>
        }
            <br /><br />
        <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>

1 个答案:

答案 0 :(得分:0)

这是创建表脚本:

USE [Breaz]
GO
/****** Object:  Table [dbo].[Applied]    Script Date: 9/6/2016 2:13:55 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Applied](
    [AppliedId] [int] IDENTITY(1,1) NOT NULL,
    [StudentId] [int] NOT NULL,
    [CourseId] [int] NOT NULL,
 CONSTRAINT [PK_Applied] PRIMARY KEY CLUSTERED 
(
    [AppliedId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[CourseDepartment]    Script Date: 9/6/2016 2:13:55 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CourseDepartment](
    [CourseDepartmentId] [int] IDENTITY(1,1) NOT NULL,
    [CourseId] [int] NOT NULL,
    [DepartmentId] [int] NOT NULL,
 CONSTRAINT [PK_CourseDepartment] PRIMARY KEY CLUSTERED 
(
    [CourseDepartmentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Courses]    Script Date: 9/6/2016 2:13:55 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Courses](
    [CourseId] [int] IDENTITY(1,1) NOT NULL,
    [CourseName] [varchar](10) NOT NULL,
 CONSTRAINT [PK_Courses] PRIMARY KEY CLUSTERED 
(
    [CourseId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Department]    Script Date: 9/6/2016 2:13:55 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Department](
    [DepartmentId] [int] IDENTITY(1,1) NOT NULL,
    [DepartmentName] [varchar](10) NOT NULL,
 CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED 
(
    [DepartmentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Student]    Script Date: 9/6/2016 2:13:55 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Student](
    [StudentId] [int] IDENTITY(1,1) NOT NULL,
    [FirstName] [varchar](10) NULL,
    [LastName] [varchar](10) NULL,
    [DateOfBirth] [datetime] NULL,
    [Address] [varchar](10) NULL,
    [PhoneNumber] [varchar](10) NULL,
    [Email] [varchar](10) NULL,
    [AppliedDate] [varchar](10) NULL,
 CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED 
(
    [StudentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Applied]  WITH CHECK ADD  CONSTRAINT [FK_Applied_Courses] FOREIGN KEY([CourseId])
REFERENCES [dbo].[Courses] ([CourseId])
GO
ALTER TABLE [dbo].[Applied] CHECK CONSTRAINT [FK_Applied_Courses]
GO
ALTER TABLE [dbo].[Applied]  WITH CHECK ADD  CONSTRAINT [FK_Applied_Student] FOREIGN KEY([StudentId])
REFERENCES [dbo].[Student] ([StudentId])
GO
ALTER TABLE [dbo].[Applied] CHECK CONSTRAINT [FK_Applied_Student]
GO
ALTER TABLE [dbo].[CourseDepartment]  WITH CHECK ADD  CONSTRAINT [FK_CourseDepartment_Courses] FOREIGN KEY([CourseId])
REFERENCES [dbo].[Courses] ([CourseId])
GO
ALTER TABLE [dbo].[CourseDepartment] CHECK CONSTRAINT [FK_CourseDepartment_Courses]
GO
ALTER TABLE [dbo].[CourseDepartment]  WITH CHECK ADD  CONSTRAINT [FK_CourseDepartment_Department] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Department] ([DepartmentId])
GO
ALTER TABLE [dbo].[CourseDepartment] CHECK CONSTRAINT [FK_CourseDepartment_Department]
GO

使用EDMX生成的模型加上此视图:

namespace Testy2.Models
{
    public class StudentView
    {
        public Student student { get; set; }
        public Applied applied { get; set; }
    }
}

这是控制器:

public class Application2Controller : Controller
{
    //
    // GET: /Application2/

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult DepartmentList()
    {
        var departments = new List<Department>();
        using (var db = new Registrars())
        {
            departments = db.Departments.OrderBy(x => x.DepartmentName).ToList();
            if (HttpContext.Request.IsAjaxRequest())
            {
                return Json(new SelectList(
                            departments,
                            "DepartmentID",
                            "DepartmentName"), JsonRequestBehavior.AllowGet
                            );
            }
        }
        return View(departments);
    }

    public ActionResult CourseList(int DepartmentID)
    {
        using (var db = new Registrars())
        {
            var courses = db.CourseDepartments.Where(x => x.DepartmentId == DepartmentID).Select(
                p => new { CourseId = p.CourseId, CourseName = p.Cours.CourseName }).ToList();
            if (HttpContext.Request.IsAjaxRequest())
                return Json(new SelectList(courses, "CourseID", "CourseName"), JsonRequestBehavior.AllowGet);
            return View(courses);
        }
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(StudentView application)
    {
        var student = new Student
        {
            StudentId = application.student.StudentId,
            FirstName = application.student.FirstName,
            LastName = application.student.LastName,
            DateOfBirth = application.student.DateOfBirth,
            Address = application.student.Address,
            PhoneNumber = application.student.PhoneNumber,
            Email = application.student.Email,
            AppliedDate = application.student.AppliedDate
        };

        var apply = new Applied
        {
            StudentId = application.student.StudentId,
            CourseId = application.applied.CourseId
        };

        if (ModelState.IsValid)
        {
            using (var db = new Registrars())
            {
                db.Students.Add(student);
                db.Applieds.Add(apply);

                db.SaveChanges();
                return RedirectToAction("Index", "Application2");
            }
        }
        return View();
    }

}

以下是观点:

@model Testy2.Models.StudentView

@{
    ViewBag.Title = "Student Appication";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Student Application Form</h2>

@using (Html.BeginForm("Create", "Application2", FormMethod.Post))
{
    @Html.AntiForgeryToken()

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

        <div class="form-group">
            @Html.LabelFor(model => model.student.StudentId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.student.StudentId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.student.StudentId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.student.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.student.FirstName)
                @Html.ValidationMessageFor(model => model.student.FirstName)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.student.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.student.LastName)
                @Html.ValidationMessageFor(model => model.student.LastName)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.student.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.student.DateOfBirth)
                @Html.ValidationMessageFor(model => model.student.DateOfBirth)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.student.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.student.Address)
                @Html.ValidationMessageFor(model => model.student.Address)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.student.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.student.PhoneNumber)
                @Html.ValidationMessageFor(model => model.student.PhoneNumber)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.student.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.student.Email)
                @Html.ValidationMessageFor(model => model.student.Email)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.student.AppliedDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.student.AppliedDate)
                @Html.ValidationMessageFor(model => model.student.AppliedDate)
            </div>
        </div>
        <br>
        <br>
        <div class="form-group">

            <label for="Departments">Departments</label>
            <select id="Departments" name="Departments"></select>
            <br /><br />

        </div>

        <div class="form-group">
            <label for="applied_CourseId">Courses</label>
            @Html.DropDownListFor(m => m.applied.CourseId, new SelectList(new List<string>()), new { id = "applied_CourseId" })
        </div>

        @section scripts {
            <script type="text/javascript">
                $(function () {
                    $.getJSON("/Application2/DepartmentList", function (data) {
                        var items = "<option>---------------------</option>";
                        $.each(data, function (i, country) {
                            items += "<option value='" + country.Value + "'>" + country.Text + "</option>";
                        });
                        $("#Departments").html(items);
                    });

                    $("#Departments").change(function () {
                        $.getJSON("@Url.Action("CourseList", "Application2")?DepartmentID=" + $("#Departments").val(), function (data) {
                            var items = "<option>---------------------</option>";
                            $.each(data, function (i, state) {
                                items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
                            });
                            $("#applied_CourseId").html(items);
                        });
                    });
                });
            </script>
        }
        <br /><br />
        <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>
相关问题