将多个值绑定到单个复选框,并将其发布到控制器 [英] Bind multiple values to a single checkbox and post it to controller

查看:188
本文介绍了将多个值绑定到单个复选框,并将其发布到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Model.cs



广告系列可以有多个图片,这就是为什么 IEnumerable< int& ImageIdList

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

View.cshtml b
$ b

我想根据 ImageIdList 下载与广告系列相关的所有图片,这就是为什么我需要发布所有这些 ImageIds

  @model Campaign 

@ {
Layout =....;
var assets = Model.AssetsInCampaign.ToList();
}
@using(Html.BeginForm(action-method,controller,FormMethod.Post))
{
< div class =btnSubmit>
< input type =submitvalue =下载资源/>
< / div>
@foreach(var i in assets)
{
< div class =s_checkcol>
< input type =checkboxname =ids/>
@foreach(var imageId in i.Where(c => c.AssetId == doc.FileDataId).SelectMany(c => c.ImageIdList))
{
& input type =hiddenname =idsvalue = @(imageId)>
}
< / div>
}
}

Controller.cs / p>

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

注意:只提供代码的一部分这里。它是一个DB第一个方法,我决不能改变它(ORDERS)。



我试过上面的,但所有的 问题:我应该如何绑定?

IEnumerable< int> View.cs 中的复选框将属性添加到 Controller.cs 以便只发布所选复选框的 ids

解决方案


这是一个很好的练习...它会工作,Iam使用这种
方式( Iam确定它会工作得很好),但你有一件事,


只是作为这个特定问题的答案。



它适用于所有stackoverflow用户。因为我从来没有在stackoverflow中找到下面的方法anyware。



我通过长时间搜索得到这个方法。



这将有助于避免for循环绑定Checkboxlist



它是可重用性的最佳好处(需要一行(最多:20-25个字符绑定Razor中的CheckBoxList ))



CheckBoxListItem.cs


创建一个新类CheckBoxListItem //可以使用任何其他名称




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

MyModel.cs b
$ b


这是modelclass




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

HomeController.cs b
$ b


这是控制器




  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})
//如果只需要int部分,字段
};
return View(model);
}

[HttpPost]
public ActionResult索引(MyModel myModel)//对PostAction的模型对象
{
IEnumerable< CheckBoxListItem> ChkList = myModel.ChkList;
//这是你的答案,你可以看到所有的复选框项目(选中和取消选中)在ChkList,它将显示所有的检查项目是真的和非检查项目是假的IsChecked字段
}




strong>


转到文件夹查看 共享 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>




创建您的视图




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)//这只有一行代码就足够绑定checkBoxList在未来

< input type = submitvalue =Createclass =/>

您将在帖子操作中获得所有这些


Model.cs

A campaign can have multiple images, that's why 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

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.

@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

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).

I tried the above, but all of the ids are posted to the controller no matter how many checkboxes are selected.

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?

解决方案

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 taking this effort not only for as an answer to this particular question.

Its for all stackoverflow users. Because i never found the below method anyware in 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

Its the best good for re-usability (need a single line (max: 20-25 chars to bind a CheckBoxList in Razor))

CheckBoxListItem.cs

create a New Class CheckBoxListItem //you can use any other names

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

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

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

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

@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

这篇关于将多个值绑定到单个复选框,并将其发布到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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