我最近开始使用ASP.NET,必须说我非常喜欢它。但是在每种关系中,您都必须在这里和那里遇到一些障碍。这是我的:

我的起始项目包括创建用于管理学生的简单学校系统。我有几个表(学生,学生地址,年级和课程)。

这是有问题的两个表:

1)学生桌:

  public Student()
        {

            this.Courses = new HashSet<Course>();
        }

        public int StudentId { get; set; }

        [Required]
        [StringLength(50, MinimumLength = 2, ErrorMessage = "The name must have over 2 and under 50 characters!")] // stavlja ograničenje na duljinu stringa u bazi
        public string Name { get; set; }

        [Required]
        [StringLength(50, MinimumLength = 2, ErrorMessage = "The name must have over 2 and under 50 characters!")]
        public string Surname { get; set; }

        public int CurrentGradeId { get; set; }
        public Grade CurrentGrade { get; set; }
        public virtual StudentAdress Address { get; set; }

        public virtual ICollection<Course> Courses { get; set; }


2)StudentAddress表:

        public int StudentId { get; set; }
        public string Address1 { get; set; }
        public string Adress2 { get; set; }
        public string City { get; set; }
        public int ZipCode { get; set; }
        public string Country { get; set; }

        public virtual Student Student { get; set; }


简而言之,当我在“学生”编辑“操作方法”时,我正在尝试更新StudentAddresses属性(更精确地说是Student的Address1属性)。

这是“编辑视图”学生:

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

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

    <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, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

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

    <div class="form-group">
        @Html.LabelFor(model => model.CurrentGradeId, "CurrentGradeId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("CurrentGradeId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CurrentGradeId, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.Address.Address1, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Address.Address1, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Address.Address1, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>


最后是“ StudentsController”的“编辑操作方法”:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "StudentId,Name,Surname,CurrentGradeId")] Student student  )
{

    if (ModelState.IsValid)
    {

        // getting student id for current studentid
        StudentAdress addresa = db.Addresses.Find(student.StudentId);

        // trying to bind input value
        addresa.Address1 = student.Address.Address1.ToString();

        // saving new value in StudentAddresses field Address1
        db.Entry(addresa).State = EntityState.Modified;
        db.SaveChanges();

        db.Entry(student).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    ViewBag.CurrentGradeId = new SelectList(db.Grades, "GradeId", "GradeName", student.CurrentGradeId);
    return View(student);
}


因此,在Edit方法中,我想在Student表的Edit方法中保存Address1的新输入值。或更简单地说,我想在编辑Student类时更新StudentAddress类中的Address1字段

更新1

因此,可以说我已经弄清楚了,但是我仍然想知道这样做是否正确和正确。

在“学生编辑”操作方法中,我添加了addresa.Address1 = Request.Form["Address.Address1"];,其中我使用属性name=Address.Address1更新了字段,这起到了技巧,但我想知道这样做是否正确?

请记住,我已经尝试过

**addresa.Address1 = student.Address.Address1;**


但是使用这种“更清洁”的方法给了我:


  System.NullReferenceException:对象引用未设置为实例
  一个对象。


我可以使用其他方法更新Address.Address1字段吗?

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "StudentId,Name,Surname,CurrentGradeId")] Student student  )
        {

            if (ModelState.IsValid)
            {


                StudentAdress addresa = db.Addresses.Find(student.StudentId);

                // newly added line
                addresa.Address1 = Request.Form["Address.Address1"];
                db.Entry(addresa).State = EntityState.Modified;
                db.SaveChanges();

                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CurrentGradeId = new SelectList(db.Grades, "GradeId", "GradeName", student.CurrentGradeId);
            return View(student);
        }

最佳答案

你的关系错了。

在您的StudentAddress模型中,我们可以看到StudentId外键,这意味着StudentStudentAddress之间的关系是一对多的。但是在您的Student模型中,您有virtual StudentAdress Address应该是ICollection<StudentAdress> Addresses

在添加/编辑中,您可以执行以下操作:

var student = context.Student.Find(1);

student.Addresses.Add(new StudentAdress {
    Address1 = "Ul. Janka Leskovara",
    City = "Pregrada",
    ZipCode = 49218,
    Country = "Hrvatska"
});

context.SaveChanges();

关于c# - 如何从ASP.NET MVC中的相关表更新表属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48355226/

10-11 13:17