选中哪个复选框(控制器)并列出结果 [英] Which checkbox is checked(controller) and results to list

查看:113
本文介绍了选中哪个复选框(控制器)并列出结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是asp.net mvc的新手.我正在制作在线视频商店应用程序.

I am new to asp.net mvc. I am making an online video store application.

我有这个观点:

用户可以在其中选择要租借的视频.视图的代码:

where users can choose which videos their gonna rent. The code for the view:

@model IEnumerable<VideoRentalSystem.Models.VideoMaintenance>

@{
    ViewBag.Title = "Index";
}

<h2>Video Rentals</h2>
<h5 style="color:red">Only available videos is shown.</h5>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Title)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Genre)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Rating)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Quantity)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.UnitsAvailable)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.RentalPrice)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Description)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Genre)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Rating)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Quantity)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UnitsAvailable)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.RentalPrice)
        </td>
        <td>
            @Html.CheckBox("Rent?", new { id= item.VideoMaintenanceID})
        </td>
    </tr>
}

</table>

<input class="btn btn-primary" type="submit" value="Rent Selected Videos" />

就像您可以在代码底部看到我添加复选框一样,我(希望如此)为该复选框提供一个ID,该ID等于文本框左侧的视频信息.我想知道的是,如果用户单击租借选定的视频"按钮,获取所有选定的视频并将其添加到控制器内部的列表中,这是有道理的吗?

Like you can see at the bottom of the code where I add the checkbox I (hopefully) give the checkbox an ID equal to the video info left of the textbox. What I want to know is how will I, if the user clicks the 'Rent Selected Videos' button, get all the selected videos and add it to a list, inside the controller-hope this makes sense?

我当前的控制器:

using System.Data;
using System.Linq;
using System.Web.Mvc;
using VideoRentalSystem.DAL;

namespace VideoRentalSystem.Controllers
{
    public class VideoRentalsController : Controller
    {
        private VideoRentalContext db = new VideoRentalContext();

        // GET: VideoRentals
        public ActionResult Index()
        {
            var available = from a in db.VideosMaintenance
                            select a;

            available = available.Where(av => av.UnitsAvailable != 0);

            return View(available);
        }
    }
}

我的视频维护模型:

//Primary Key
        public int VideoMaintenanceID { get; set; }

        [StringLength(60, MinimumLength = 3, ErrorMessage = "A maximum of 60 and a minimum of 3 characters is allowed")]
        [Required(ErrorMessage = "This field is required")]
        public string Title { get; set; }


        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$", ErrorMessage = "Only letters is allowed")]
        [Required(ErrorMessage = "This field is required")]
        [StringLength(140, ErrorMessage = "A maximum of 140 characters is allowed")]
        public string Description { get; set; }

        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$", ErrorMessage = "Only letters is allowed")]
        [Required(ErrorMessage = "This field is required")]
        [StringLength(30, ErrorMessage = "A maximum of 30 characters is allowed")]
        public string Genre { get; set; }

        [StringLength(15, ErrorMessage = "A maximum of 15 characters is allowed")]
        public string Rating { get; set; }

        [RegularExpression(@"^[0-9]+$", ErrorMessage = "Only numbers is allowed")]
        [Required(ErrorMessage = "This field is required")]
        public int Quantity { get; set; }

        [Display(Name = "Units Available")]
        [RegularExpression(@"^[0-9]+$", ErrorMessage = "Only numbers is allowed")]
        [Required(ErrorMessage = "This field is required")]
        public int UnitsAvailable { get; set; }

        [Display(Name = "Rental Price")]
        [Range(1, 100, ErrorMessage = "Range between 1,100")]
        [DataType(DataType.Currency)]
        public decimal RentalPrice { get; set; }

        //Foreign Key
        public virtual ICollection<CustomerMaintenance> CustomersMaintenance { get; set; }
    }

...以及我的CustomerMaintenance模型:

...and my model for CustomerMaintenance:

//Primary Key
        [Display(Name = "Identification Number")]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [Required(ErrorMessage = "This field is required")]
        [RegularExpression(@"^[0-9]+$", ErrorMessage = "Only numbers is allowed")]
        public string CustomerMaintenanceID { get; set; }

        [StringLength(30, ErrorMessage = "A maximum of 30 characters is allowed")]
        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$", ErrorMessage = "Only letters is allowed")]
        [Required(ErrorMessage = "This field is required")]
        public string Name { get; set; }

        [StringLength(60, ErrorMessage = "A maximum of 60 characters is allowed")]
        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$", ErrorMessage = "Only letters it allowed")]
        [Required(ErrorMessage = "This field is required")]
        public string Surname { get; set; }

        [StringLength(250, ErrorMessage = "A maximum of 250 characters is allowed")]
        //[RegularExpression(@"^[A-Z]+[0-9]+[a-zA-Z''-'\s]*$")]
        [Required(ErrorMessage = "This field is required")]
        [Display(Name = "Physical Address")]
        public string Address { get; set; }

        [StringLength(10, ErrorMessage = "A maximum of 10 characters is allowed")]
        [RegularExpression(@"^[0-9]+$", ErrorMessage = "Only numbers allowed")]
        [Required(ErrorMessage = "This field is required")]
        [Display(Name = "Phone Number")]
        public string PhoneNumber { get; set; }

        //Foreign Key
        public virtual VideoMaintenance VideosMaintenance { get; set; }

我的DbContext:

My DbContext:

using System.Data.Entity;
using VideoRentalSystem.Models;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace VideoRentalSystem.DAL
{
    public class VideoRentalContext : DbContext
    {
        //Passes name of the connnection string to the constructor
        public VideoRentalContext() : base("VideoRentalContext")
        {

        }

        public DbSet<CustomerMaintenance> CustomersMaintenance { get; set; }
        public DbSet<VideoMaintenance> VideosMaintenance { get; set; }

        //Override entity naming convention- disable pluralisation 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>();
        }
    }
}

对于这个冗长的问题,我深表歉意!任何帮助将不胜感激!

I apologize for this long question! Any help will be appreciated!

推荐答案

一个很好的用例,它可以使用编辑器模板.

Looks like a great use case to make use of Editor Templates.

为您的视图创建这样的视图模型.

Create a view model like this for your view.

public class RentVideoVM
{       
    public List<VideoSelection> Videos { set; get; } 
    //Add other properties needed for your view.
}

public class VideoSelection
{
    public int VideoId { set; get; }
    public string Name { set; get; }   

    public bool IsSelected { set; get; }
   //Add other properties needed for your view.
}

VideoSelection类的IsSelected属性用于在用户界面的复选框上存储用户选择.

The IsSelected property of VideoSelection class is used to store users selection on the check box from the UI.

现在,在您的GET操作方法中,创建RentVideoVM视图模型的实例,加载视频集合并将其发送到视图,

Now in your GET action method, create an instance of the RentVideoVM viewmodel, Load the Videos collection and send it to the view,

public ActionResult Register()
{
    var vm = new RentVideoVM();
    vm.Videos = db.Videos.Select(s => new VideoSelection
    {
        VideoId = s.VideoId,
        Name = s.VideoName
    }).ToList();
    return View(vm);
}

将其更改为db.YourWhateverDBSet而不是db.Videos

Change it db.YourWhateverDBSet instead of db.Videos

现在,我们需要创建一个编辑器模板.转到Views文件夹,然后进入当前控制器的文件夹,并创建一个名为"EditorTemplates"的子文件夹.在此处添加一个名为VideoSelection.cshtml的新视图,并在其中添加以下代码.

Now we need to create an editor template. Go to Views folder and go inside the folder for your current controller and create a sub folder called "EditorTemplates". Add a new view there with the name VideoSelection.cshtml and have the below code there.

@model YourNamespace.VideoSelection
<div>
    @Model.Name

    @Html.CheckBoxFor(d=>d.IsSelected)

    @Html.HiddenFor(s => s.VideoId)
</div>

您可以根据需要更改html标记.花哨!

You may change the html markup however you want. Make it fancy !

现在在绑定到我们的RentVideoVM视图模型的主视图中,调用Html.EditorFor帮助器方法以显示带有复选框的视频.

Now in your main view, which is bound to our RentVideoVM view model , call the Html.EditorFor helper method to render the Videos with checkboxes.

@model YourNamespace.RentVideoVM
@using (Html.BeginForm())
{
    @Html.EditorFor(s=>s.Videos)
    <input type="submit"/>
}

您的HttpPost操作将用于处理表单发布

And your HttpPost action to handle the form posting would be

[HttpPost]
public ActionResult Register(RentVideoVM model)
{
   //check model.Videos collection
   // to do : Save and redirect
   // If something wrong happened, reload Videos collection 
    return View(model);
}

当用户发布表单时,您可以检查发布的模型的Videos集合.对于用户检查的那些视频,IsSelected属性将为true.

When user posts the form, you can inspect the Videos collection of the posted model. IsSelected property will be true for those videos which user checked.

这篇关于选中哪个复选框(控制器)并列出结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆