【问题标题】:Foreign key passing as NULL. ASP .NET MVC外键作为 NULL 传递。 ASP .NET MVC
【发布时间】:2020-06-08 21:07:42
【问题描述】:

我正在尝试使用 ASP .NET MVC 5 和 SQL Server 2012 以及数据库优先方法来开发简单的学校管理系统。

student 实体与实体类相关,因为每个学生都会被注册到一个类中。所以有一个“类”类型变量和类表的 FK 作为我的学生实体的属性。

创建学生视图有一个下拉列表,显示学生可以注册的课程。下拉列表填充得足够精细,但是当学生创建并在索引视图中查看时,其课程为 NULL。当我在服务器管理工​​作室检查创建的学生的 FK 时,我发现 FK 被作为 NULL 传递。

谁能告诉我我在这里做错了什么。

PS。我是 ASP .NET 的新手,我没有使用视图模型,因为我遵循的教程没有,也因为我觉得不需要制作一个。

这是我的 Student.cs

using System;
using System.Collections.Generic;

public partial class Student
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Student()
    {
        this.Attendences = new HashSet<Attendence>();
    }

    public int St_id { get; set; }
    public string St_name { get; set; }
    public string St_guardian_name { get; set; }
    public string St_guardian_relation { get; set; }
    public string St_guardian_contact { get; set; }
    public string St_address { get; set; }
    public System.DateTime St_dob { get; set; }
    public Nullable<int> St_cl_fk_id { get; set; }
    public int St_status { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Attendence> Attendences { get; set; }
    public virtual Class Class { get; set; }
}

这是我在 StudentsController 中的 Create Action。 PopulateClassDropDown 是一个辅助方法。

 private void PopulateClassDropDownList(object selectedClass = null)
    {
        var classQuery = from c in db.Classes
                         where c.Cl_status==1
                               select c;
        ViewBag.classID = new SelectList(classQuery, "Cl_id", "Cl_name", selectedClass);
    }
    [Authorize]

    // GET: Students/Create
    public ActionResult Create()
    {

        PopulateClassDropDownList();
        return View();
    }

    // POST: Students/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.
    [Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "St_id,St_name,St_guardian_name,St_guardian_relation,St_guardian_contact,St_address,St_dob,St_cl_fk_id.St_status")] Student student)
    {
        try
        {
            var temp = student.St_cl_fk_id;
            if (ModelState.IsValid)
            {
                student.St_status = 1;
                db.Students.Add(student);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        catch (RetryLimitExceededException /* dex*/ )
        {
            //Log the error (uncomment dex variable name and add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }


        PopulateClassDropDownList(student.St_cl_fk_id);

        return View(student);
    }

最后是学生的创建视图。

@model GMASchoolProject.Models.Student

@{
    ViewBag.Title = "Create";
}

<link rel="stylesheet" type="text/css" href="~/Content/Site.css">


<div class="row" style="margin-bottom:5px;">
    <div class="col-lg-12">
        <h1 class="page-header">Create New Student</h1>
    </div>
    <!-- /.col-lg-12 -->
</div>
<!-- /.row -->

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="row">
        <div class="col-lg-8 col-lg-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">
                    Fill in Details
                </div>
                <div class="panel-body">
                    <div class="row">
                        <form class="col-lg-6" role="form">

                            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                            <div class="form-group" style="margin:15px;">
                                @Html.LabelFor(model => model.St_name, "Student Name", htmlAttributes: new { @class = "control-label" })
                                <div>
                                    @Html.EditorFor(model => model.St_name, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.St_name, "", new { @class = "text-danger" })
                                </div>
                            </div>


                            <div class="form-group" style="margin:15px;">
                                @Html.LabelFor(model => model.St_guardian_name, "Name of Guardian", htmlAttributes: new { @class = "control-label " })
                                <div>
                                    @Html.EditorFor(model => model.St_guardian_name, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.St_guardian_name, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            <div class="form-group" style="margin:15px;">
                                @Html.LabelFor(model => model.St_guardian_relation, "Guardian's Relation", htmlAttributes: new { @class = "control-label" })
                                <div>
                                    @Html.DropDownListFor(model => model.St_guardian_relation, new[] {
                                                                                   new SelectListItem() {Text="Parents", Value="Parents" },
                                                                                   new SelectListItem() {Text="Other", Value="Other" }
                                    },"Choose an option", new { @class = "form-control" })

                                    @Html.ValidationMessageFor(model => model.St_guardian_relation, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            <div class="form-group" style="margin:15px;">
                                @Html.LabelFor(model => model.St_guardian_contact, "Guardian's Contact", htmlAttributes: new { @class = "control-label" })
                                <div>
                                    @Html.EditorFor(model => model.St_guardian_contact, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.St_guardian_contact, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            <div class="form-group" style="margin:15px;">
                                @Html.LabelFor(model => model.St_address, "Student's Address", htmlAttributes: new { @class = "control-label" })
                                <div>
                                    @Html.TextAreaFor(model=>model.St_address, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.St_address, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            <div class="form-group" style="margin:15px;">
                                @Html.LabelFor(model => model.St_dob, "Student's Date of Birth", htmlAttributes: new { @class = "control-label" })
                                <div>
                                    @Html.EditorFor(model => model.St_dob, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.St_dob, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            <div class="form-group" style="margin:15px;">
                                <label class="control-label col-md-2" for="ClassID">Class</label>
                                <div>
                                   @Html.DropDownList("classID", null, htmlAttributes: new { @class = "form-control" })
                                    @Html.ValidationMessageFor(model => model.St_cl_fk_id, "", new { @class = "text-danger" })
                                </div>
                            </div>

                            <div class="form-group" style="margin:15px,0,15px,0;">
                                <div class="col-md-offset-5 col-md-2">
                                    <input type="submit" value="Create" class="btn btn-primary" />
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>


}
<div>
    @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-danger" })
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}




【问题讨论】:

    标签: c# asp.net asp.net-mvc


    【解决方案1】:

    基于this,进行以下更改:

    // classId implies a scalar value, this should be a list
    ViewBag.classList = new SelectList(classQuery, "Cl_id", "Cl_name", selectedClass);
    
    // Change your dropdown code:
    @Html.DropDownList("St_cl_fk_id", (SelectList)ViewBag.classList, htmlAttributes: new { @class = "form-control" })
    // or better yet:
    @Html.DropDownListFor(m => m.St_cl_fk_id, (SelectList)ViewBag.classList, new { @class = "form-control" })
    
    // remove this line - it should bind automatically
    var temp = student.St_cl_fk_id;
    

    【讨论】:

    • 当我使用 DropDownList 帮助程序时,我收到以下错误 CS1973:“HtmlHelper”没有名为“DropDownList”的适用方法,但似乎具有该名称的扩展方法。扩展方法不能动态调度。考虑强制转换动态参数或调用扩展方法而不使用扩展方法语法。
    • 与 DropDownListFor CS1928 有点相同:“HtmlHelper”不包含“DropDownListFor”的定义和最佳扩展方法重载“SelectExtensions.DropDownListFor(HtmlHelper , Expression>, IEnumerable, object)' 有一些无效参数
    • 我的错,您需要将 viewbag 转换为选择列表。查看修改后的代码。
    猜你喜欢
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多