Как добавить студента в таблицу посещаемости - PullRequest
0 голосов
/ 28 февраля 2020

Я хочу добавить учеников в Таблицу посещаемости через контроллер Class_Schedule. Для этого я создал Publi c ActionResult:

public ActionResult Register(int? id)           
{
  if (id == null)
  {
     return RedirectToAction("Index");
  }
  Class_Schedule class_Schedule = db.Class_Schedule.Find(id);
  if (class_Schedule == null)
  {
     return RedirectToAction("Index");
  }
  //This is the collects the class_schedule ID to make the attendance specific for each class ViewBag.CSid = id;
  ViewBag.studentID = new SelectList(db.Students, "StudentID", "Full_Name");
  ViewBag.instructorID = new SelectList(db.Instructors, "InstructorID", "Name");
  var attendances = db.Attendances;

  return View(attendances.ToList());
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register([Bind(Include = "AttendanceID,csID,InstructorID,StudentID")] Attendance attendance)
{
  try
  {
    if (ModelState.IsValid)
    {
      db.Attendances.Add(attendance);
      db.SaveChanges();
      //ViewBag.msg = "Instructor Added";
      return RedirectToAction("Register");
    }
    return View(attendance);
   }
   catch
   {
     return View(attendance);
   }
}

Это мое мнение:

@model IEnumerable<BBM.Models.Attendance>

@{
    ViewBag.Title = "Register";
}

<h2>Class Schedule @ViewBag.CSid</h2>

@using (Html.BeginForm("Register","Class_Schedule", FormMethod.Post))
{
@Html.AntiForgeryToken()


<div class="form-group">
    @{
        var studentid = Model.Select(model => model.StudentID.ToString());
    }
    @Html.Label("StudentID", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("StudentID", null, htmlAttributes: new { @class = "form-control" })
    </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>
<h4>Student register</h4>
<table class="table">
    <tr>

        <th>
            Attendance ID
        </th>
        <th>
            Student ID
        </th>
        <th>
            Student Name
        </th>
        <th>
            Expiry Date
        </th>
    </tr>
    @if (Model != null)
    {

        foreach (var item in Model.Where(p => p.csID.Equals(ViewBag.csID)))
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.AttendanceID)
                </td>

                <td>
                    @Html.DisplayFor(modelItem => item.StudentID)
                </td>

                <td>
                    @Html.DisplayFor(modelItem => item.Student.Full_Name)
                </td>

                <td>
                    @if (item.Student.Payments != null && item.Student.Payments.Any(p => p.Expires > DateTime.Now))
                    {
                        @Html.DisplayFor(modelItem => item.Student.Payments.OrderByDescending(p => p.paymentID).First(p => p.Expires > DateTime.Now).Expires)
                    }
                    else
                    {
                        @Html.DisplayName("Expired");
                    }
                </td>

            </tr>
        }
    }
</table>
     @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
     }

В этом представлении есть список выбора, чтобы выбрать студентов, которых вы хотите добавить, но но идентификатор студента не входит в параметр и postMethod не происходит This is the view as you can see you can select the students but the create or submit buttons don't work

Те, которые уже есть, предназначены для тестирования, и я сделал их через sql сервер

1 Ответ

0 голосов
/ 28 февраля 2020

У вас есть только указанный раскрывающийся идентификатор и атрибут html. вы забыли передать данные в раскрывающийся список помощников при заполнении поля ViewBag. Обновление, как показано ниже для студента

@Html.DropDownList("StudentID",htmlAttributes:new { @class = "control-label col-md-2" },selectList:new SelectList(ViewBag.studentID))

Пожалуйста, убедитесь, что вы получаете studentId по методу записи.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...