简体   繁体   English

将多个值绑定到单个复选框,并将其发布到控制器

[英]Bind multiple values to a single checkbox and post it to controller

Model.cs Model.cs

A campaign can have multiple images, that's why IEnumerable<int> ImageIdList . 一个广告系列可以包含多个图像,这就是IEnumerable<int> ImageIdList的原因。

public class Campaign
{
  public int Id { get; set; }
  public int CreatedBy { get; set; }
  public int UpdatedBy { get; set; }
  public IEnumerable<int> ImageIdList { get; set; }
}

View.cshtml View.cshtml

I want to download all the images related to a campaign, based on the ImageIdList , that's why I need to post all these ImageIds when a particular Campaign is checked and download button is clicked. 我想基于ImageIdList下载与广告系列相关的所有图像,这就是为什么ImageIds特定广告系列并单击下载按钮时,我需要发布所有这些ImageIds的原因。

@model Campaign

    @{
      Layout = "....";
      var assets = Model.AssetsInCampaign.ToList();
    }
    @using (Html.BeginForm("action-method", "controller", FormMethod.Post))
    {
      <div class="btnSubmit">
        <input type="submit" value="Download Asset(s)" />
      </div>
      @foreach(var i in assets)
      {
        <div class="s_checkcol">
          <input type="checkbox" name="ids" />
          @foreach (var imageId in i.Where(c => c.AssetId == doc.FileDataId).SelectMany(c => c.ImageIdList))
          {
              <input type="hidden" name="ids" value=@(imageId)>
          }
        </div>
      }
    }

Controller.cs Controller.cs

public ActionResult DownloadFiles(IEnumerable<int> ids)
{
    // code
}

NOTE: Only a part of code(where I'm facing the problem) is provided here. 注意:此处仅提供一部分代码(我正面临问题的地方)。 Its a DB first approach and in no way I can alter that (ORDERS). 它是数据库优先的方法,我绝不能改变它(ORDERS)。

I tried the above, but all of the ids are posted to the controller no matter how many checkboxes are selected. 我尝试了上面的方法,但是无论选择了多少个复选框,所有ids发布到控制器中。

Question: How should I bind the IEnumerable<int> ImageIdList property to a checkbox in View.cs and post the data to Controller.cs so that only the ids of selected checkboxes are posted? 问:我应该如何绑定IEnumerable<int> ImageIdList在属性复选框View.cs和发布数据Controller.cs使得只有ids选择复选框张贴?

This is a nice practice... it will work and Iam working with such a manner ( Iam sure that it will work very well ) but one thing you have to be very carefull while coding this , little bit complicated 这是一个很好的实践...它会起作用,而Iam会以这种方式工作( 我敢肯定它会很好地工作 ),但是在编写此代码时 ,您必须非常小心 ,有点复杂

Iam taking this effort not only for as an answer to this particular question. Iam不仅是为了回答这个特定问题而付出了很多努力。

Its for all stackoverflow users. 适用于所有stackoverflow用户。 Because i never found the below method anyware in stackoverflow. 因为我从未在stackoverflow中找到以下方法的任何软件。

I get this method by a long search. 我经过长时间的搜寻才知道这种方法。 You people can use this. 你们可以使用这个。

It will help you to avoid for loops to bind the Checkboxlist 这将帮助您避免for循环绑定Checkboxlist

Its the best good for re-usability ( need a single line (max: 20-25 chars to bind a CheckBoxList in Razor )) 它对可重用性最好( 需要一行(最多:20-25个字符以绑定Razor中的CheckBoxList ))

CheckBoxListItem.cs CheckBoxListItem.cs

create a New Class CheckBoxListItem //you can use any other names 创建一个新类CheckBoxListItem //您可以使用任何其他名称

public class CheckBoxListItem
{
    public int ID { get; set; }
    public string Display { get; set; }
    public bool IsChecked { get; set; }
}

MyModel.cs MyModel.cs

This is modelclass 这是模型类

public class MyModel
{
    [Key]        
    public int Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<CheckBoxListItem> ChkList { get; set; }
}

HomeController.cs HomeController.cs

This is controller 这是控制器

public ActionResult Index()
{
     var model = new MyModel(){
         Id = 0,
         Name = "Your Name",
         ChkList = dbContext.myTable.Select(x => new CheckBoxListItem { ID = x.MyTableFieldID, Display = x.MyTableFieldName, IsChecked = true })
         //If you need only int part, then just avoid to bind data on Display field
     };
     return View(model);
}

[HttpPost]
public ActionResult Index(MyModel myModel) //Your model object on PostAction
{
    IEnumerable<CheckBoxListItem> ChkList = myModel.ChkList; 
    // Here is your answer, You can see all your check box items (both checked and unchecked) in ChkList, it will shows all your checked items are true and non-checked items are false in IsChecked field 
}

Here you have to give more patiance 在这里,您必须给予更多的耐心

Goto the Folder View > Shared > EditorTemplates and RightClick Add>View... and Create a new View with the same name CheckBoxListItem.cshtml 转到文件夹视图 > 共享 > EditorTemplates,然后右键单击添加>视图...,然后使用相同的名称 CheckBoxListItem.cshtml创建一个新视图

CheckBoxListItem.cshtml CheckBoxListItem.cshtml

@model Project.Models.CheckBoxListItem
<div class="">
    @Html.HiddenFor(x => x.ID)
    <div class="">
        @Html.CheckBoxFor(x => x.IsChecked)
    </div>
    @Html.LabelFor(x => x.IsChecked, Model.Display, new { @class = "" })
</div>

Create your View 创建您的视图

Index.cshtml Index.cshtml

@model @model Project.Models.MyModel

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

@Html.EditorFor(model => model.ChkList) //This only one line of code is enough to bind a checkBoxList in future

<input type="submit" value="Create" class="" />

You will get all these in your post action 您将在后续操作中获得所有这些

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM