如何从 HttpPost Create 操作方法中知道选定的复选框? [英] How to know the selected checkboxes from within the HttpPost Create action method?

查看:33
本文介绍了如何从 HttpPost Create 操作方法中知道选定的复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在StudentCourse 之间存在多对多关系.链接实体集是Enrollment.为了简单起见,它们都定义如下.

型号

公开课课程{公共 int Id { 获取;放;}公共字符串标题{获取;放;}公共虚拟 ICollection<Enrollment>招生{得到;放;}}公开课报名{公共 int Id { 获取;放;}公共 int StudentId { 获取;放;}公共 int CourseId { 获取;放;}公共虚拟学生学生{得到;放;}公共虚拟课程课程{ get;放;}}公开课学生{公共 int Id { 获取;放;}公共字符串名称 { 获取;放;}公共虚拟 ICollection<Enrollment>招生{得到;放;}}

视图模型

公共类StudentCourseVM{公共学生学生{得到;放;}公共 IEnumerable<课程>SelectedCourses { 得到;放;}公共 IEnumerable<课程>可用课程 { 得到;放;}}

控制器

 public IActionResult Create(){var availableCourses = context.Courses;返回视图(新的 StudentCourseVM { AvailableCourses = availableCourses });}[HttpPost]公共异步任务创建(StudentCourseVM sc){如果(模型状态.IsValid){//我应该在这里做什么?//======================等待 context.SaveChangesAsync();return RedirectToAction("索引");}返回视图(sc);}

观看次数

@model MasterDetails.ViewModels.StudentCourseVM<form asp-action="创建"><div><label asp-for="@Model.Student.Name"></label><input asp-for="@Model.Student.Name"/>

<div><label asp-for="@Model.Student.Enrollments"></label><br/>@foreach(Model.AvailableCourses 中的 var 课程){<input type="checkbox" name="@course.Title" id="@course.Id"/>@course.Title <br/>}

<输入类型=提交"值=创建"/></表单>

问题

如何从 HttpPost Create 操作方法中知道选中的复选框?

解决方案

您可以使用编辑器模板来做到这一点.

首先,为课程选择创建一个新类并更新您的视图模型以包含该类的集合.

公共类SelectedCourse{公共 int Id { 获取;放;}公共字符串名称 { 获取;放;}public bool IsSelected { 获取;放;}}公开课 StudentCourseVM{公共 int StudentId { 设置;得到;}公共 IEnumerableSelectedCourses { 得到;放;}}

您不需要将实体模型中的所有属性复制并粘贴到视图模型中.视图模型只需要视图绝对需要的那些属性.我假设您想为特定学生分配课程

现在转到您的 ~/Views/YourControllerName 并创建一个名为 EditorTemplates 的目录.在那里创建一个新的 razor 文件并命名为 SelectedCource.cshtml

将此代码粘贴到新文件中

@model SelectedCourse<label>@Model.Name</label><input asp-for="IsSelected"/><input type="hidden" asp-for="Id"/>

现在在您的 GET 操作中,创建视图模型的对象,加载 SelectedCourses 集合并将其发送到视图.

public IActionResult Create(){//我在这里硬编码了学生 ID 和课程.//您可以将其替换为真实数据.var vm = new StudentCourseVM { StudentId = 12 };//假设我们给id为12的学生分配课程vm.SelectedCourses = new List(){new SelectedCourse {Id = 1, Name = "CSS"},new SelectedCourse {Id = 2, Name = "Swift"},new SelectedCourse {Id = 3, Name = "IOS"},新的 SelectedCourse {Id = 4, Name = "Java"}};返回视图(vm);}

现在在您的主视图 (Create.cshtml) 中,它是强类型到 StudentCourseVM,在 SelectedCourses 属性上使用 EditorFor 辅助方法.

@model StudentCourseVM<form asp-action="创建">@Html.EditorFor(f=>f.SelectedCourses)<input type="hidden" asp-for="StudentId"/><输入类型=提交"/></表单>

编辑器模板将为 SelectedCourses 集合中的每个项目执行编辑器模板文件中的代码.因此,您将拥有课程名称和用户可见的复选框.

在您的 HttpPost 操作方法中,您可以使用与参数相同的视图模型.提交表单时,您可以遍历 SelectedCourses 属性中的项目,检查 IsSelected 属性值.用户在 ui 中选择的课程将具有 true 值.

[HttpPost]公共 IActionResult 创建(StudentCourseVM 模型){var studentId = model.StudentId;foreach (var modelSelectedCourse in model.SelectedCourses){if (modelSelectedCourse.IsSelected){//这个被选中了.保存到数据库}}//要做:返回一些东西}

在页面加载时预先选择一些复选框

有时您希望在页面加载时预先选择一些复选框(例如:对于您的编辑屏幕,您希望将已保存的课程显示为选中状态).为此,您只需在 GET 操作方法中将相应 SelectedCourse 对象的 IsSelected 属性设置为 true.

public IActionResult Edit(int id){//我在这里硬编码了学生 ID 和课程.//您可以将其替换为真实数据.var vm = new StudentCourseVM { StudentId = id };//假设我们给id为12的学生分配课程vm.SelectedCourses = new List(){new SelectedCourse {Id = 1, Name = "CSS"},new SelectedCourse {Id = 2, Name = "Swift", IsSelected = true },new SelectedCourse {Id = 3, Name = "IOS", IsSelected = true },新的 SelectedCourse {Id = 4, Name = "Java"}};返回视图(vm);}

以上代码将预先选中SwiftIOS 的复选框.

I have many-to-many relationship between Student and Course. The linking entity set is Enrollment. For the sake of simplicity, they are all defined as follows.

Models

public class Course
{
    public int Id { get; set; }
    public string Title { get; set; }

    public virtual ICollection<Enrollment> Enrollments { get; set; }
}

public class Enrollment
{
    public int Id { get; set; }
    public int StudentId { get; set; }
    public int CourseId { get; set; }

    public virtual Student Student { get; set; }
    public virtual Course Course { get; set; }
}

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Enrollment> Enrollments { get; set; }
}

ViewModels

public class StudentCourseVM
{
    public Student Student { get; set; }
    public IEnumerable<Course> SelectedCourses { get; set; }
    public IEnumerable<Course> AvailableCourses { get; set; }
}

Controllers

    public IActionResult Create()
    {
        var availableCourses = context.Courses;
        return View(new StudentCourseVM { AvailableCourses = availableCourses });
    }


    [HttpPost]
    public async Task<IActionResult> Create(StudentCourseVM sc)
    {
        if (ModelState.IsValid)
        {
            // What should I do here?
            // ======================
            await context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(sc);
    }

Views

@model MasterDetails.ViewModels.StudentCourseVM
<form asp-action="Create">
    <div>
        <label asp-for="@Model.Student.Name"></label>
        <input asp-for="@Model.Student.Name" />
    </div>
    <div>
        <label asp-for="@Model.Student.Enrollments"></label><br />
        @foreach (var course in Model.AvailableCourses)
        {
            <input type="checkbox" name="@course.Title" id="@course.Id" /> @course.Title <br />
        }
    </div>
    <input type="submit" value="Create" />
</form>

Questions

How to know the selected check boxes from within the HttpPost Create action method?

解决方案

You can use Editor Templates to do this.

First, create a new class for the course selection and update your view model to have a collection of that class.

public class SelectedCourse
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

public class StudentCourseVM
{
    public int StudentId { set; get; }       
    public IEnumerable<SelectedCourse> SelectedCourses { get; set; }
}

You do not need to copy and paste all the properties from your entity model to your view model. View model needs only those properties which the view absolutely need. I am assuming you want to assign courses to a specific student

Now go to your ~/Views/YourControllerName and create a directory called EditorTemplates. Create a new razor file there and give the name SelectedCource.cshtml

Paste this code to the new file

@model SelectedCourse
<label>@Model.Name</label>
<input asp-for="IsSelected"/>
<input type="hidden" asp-for="Id" />

Now in your GET action, create an object of the view model, load the SelectedCourses collection and send it to the view.

public IActionResult Create()
{
    // I hard coded the student id and the courses here.
    // you may replace it with real data.
    var vm = new StudentCourseVM { StudentId = 12 }; 
    //Assuming we are assigning courses to the student with id 12
    vm.SelectedCourses = new List<SelectedCourse>()
    {
        new SelectedCourse {Id = 1, Name = "CSS"},
        new SelectedCourse {Id = 2, Name = "Swift"},
        new SelectedCourse {Id = 3, Name = "IOS"},
        new SelectedCourse {Id = 4, Name = "Java"}
    };
    return View(vm);
}

Now in your main view(Create.cshtml) which is strongly typed to StudentCourseVM,Use EditorFor helper method on the SelectedCourses property.

@model StudentCourseVM
<form asp-action="Create">   
    @Html.EditorFor(f=>f.SelectedCourses)
    <input type="hidden" asp-for="StudentId"/>
    <input type="submit"/>
</form>

The Editor template will execute code in the editor template file for each item in the SelectedCourses collection. So you will have the course name and a checkbox visible to the user.

In your HttpPost action method, you can use the same view model as the parameter. When the form is submitted, you may loop through the items in SelectedCourses property check the IsSelected property value. The courses user selected in the ui will have a true value.

[HttpPost]
public IActionResult Create(StudentCourseVM model)
{
    var studentId = model.StudentId; 
    foreach (var modelSelectedCourse in model.SelectedCourses)
    {
        if (modelSelectedCourse.IsSelected)
        {
            //this one is selected. Save to db
        }
    }
    // to do : Return something
}

Pre-selecting some checkboxes on page load

Sometimes you want to pre select some checkboxes when the page loads (Ex : For your edit screen you want to show already saved courses as checked). To do this, you simply need to set the IsSelected property of the corresponding SelectedCourse object to true in your GET action method.

public IActionResult Edit(int id)
{
    // I hard coded the student id and the courses here.
    // you may replace it with real data.
    var vm = new StudentCourseVM { StudentId = id }; 
    //Assuming we are assigning courses to the student with id 12
    vm.SelectedCourses = new List<SelectedCourse>()
    {
        new SelectedCourse {Id = 1, Name = "CSS"},
        new SelectedCourse {Id = 2, Name = "Swift", IsSelected = true },
        new SelectedCourse {Id = 3, Name = "IOS", IsSelected = true },
        new SelectedCourse {Id = 4, Name = "Java"}
    };
    return View(vm);
}

The above code will pre select the checkboxes for Swift and IOS.

这篇关于如何从 HttpPost Create 操作方法中知道选定的复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆