[英]Can a ViewBag.Something transport data from view to the controller as well?
[英]How to pass a specific ViewBag SelectList data from view to controller and then in Repository
在进行创建和更新操作时,我需要将部门表中的 DeptId 传递给学生表。 我怎样才能做到这一点。
我在存储库中的 AddStudent 方法
public void AddStudents(Student student)
{
context.Students.Add(student);
context.SaveChanges();
}
学生控制器中的获取和发布方法
public IActionResult Create()
{
var departments=departmentRepository.GetAllDepartmentList();
ViewBag.Departments = new SelectList(departments, "DeptId", "DeptName");
return View();
}
[HttpPost]
public IActionResult Create(Student student)
{
if (ModelState.IsValid)
{
repository.AddStudents(student);
return RedirectToAction("Index");
}
return View();
}
创建.cshtml
<form asp-action="Create">
<div class="form-group">
<label class="control-label">Department Name</label>
<select asp-items="@ViewBag.Departments" class="form-control">
</select>
</div>
<div class="btn-group pt-4">
@*also have other fields*@
<a asp-action="Index" class="btn btn-primary">Back to List</a> </div>
</form>
StudentViewModel.cs 用于查看和获取两个表中的数据
如何也传递相同的 DeptId 进行更新操作。 这是获取特定学生记录的代码,它工作正常,但不知道如何更新
public StudentViewModel GetStudentById(int id)
{
var students = context.Students.Join(context.Departments, stud => stud.DeptId, dept => dept.DeptId, (stud, dept) => new StudentViewModel
{
StudId = stud.StudId,
StudentName = stud.StudentName,
Age = stud.Age,
Gender = stud.Gender,
DOB = stud.DOB,
Email = stud.Email,
Address = stud.Address,
DeptId = stud.DeptId,
DeptName = dept.DeptName
}).Where(stud => stud.StudId.Equals(id)).FirstOrDefault();
return students;
}
更新方法不起作用:
public void UpdateStudents(Student student)
{
context.Students.Update(student);
context.SaveChanges();
}
如何通过相同的 DeptId 进行更新操作
在您的创建视图中,请尝试以下操作:
<form asp-action="Create">
<div class="form-group">
<label name="DeptId" class="control-label">Department Name</label>
<select name="DeptId" class ="form-control" asp-items="@ViewBag.Departments" ></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
在您的创建操作中添加参数DeptId
[HttpPost]
public IActionResult Create(Student student, string DeptId)
{...
TempData["AA"] = DeptId;
}
并在您的更新操作中添加以下内容以从创建帖子操作中获取DeptId
int DEPID = (int)TempData["AA"];
Create 现在以这种方式工作:
编辑了我的 Create post 方法,如下所示:
public IActionResult Create(StudentViewModel model)
{
if (ModelState.IsValid)
{
Student student = new Student
{
StudentName = model.StudentName,
Gender = model.Gender,
DOB = model.DOB,
Age = model.Age,
Email = model.Email,
Address = model.Address,
DeptId = model.DeptId
};
repository.AddStudents(student);
return RedirectToAction("Index");
}
return View();
}
然后在我的 Create.cshtml 中添加了 asp-for:
@model StudentViewModel
@*..Other fields...*@
<select asp-for="DeptId" asp-items="@ViewBag.Departments" class="form-control">
在 StudentViewModel 中也使 DeptName 可以为空
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.