【问题标题】:Using ViewBag with @Html.CheckBoxFor rather than "plain" <input type= "checkbox">将 ViewBag 与 @Html.CheckBoxFor 一起使用,而不是“plain”<input type="checkbox">
【发布时间】:2021-11-02 21:36:42
【问题描述】:

已经在View 中使用了@Html.CheckBoxFor,我计划在同一个View 中将Tag HelperViewBag 一起使用,以规避一些错误(例如变量定义):

型号

   public class test
    {
      public int ItemID { get; set; }
      public string ItemName { get; set; }
      public bool IsAvailable { get; set; }
    }

控制器

List<test> ItemList = new List<test>();
         ItemList.Add(new test {ItemID=1, ItemName="apple", IsAvailable = false});
         ItemList.Add(new test {ItemID=2, ItemName="mango", IsAvailable = false});
         ItemList.Add(new test {ItemID=3, ItemName="stuck", IsAvailable = false});
         ItemList.Add(new test {ItemID=4, ItemName="blocked", IsAvailable = false});
         ItemList.Add(new test {ItemID=5, ItemName="help:(", IsAvailable = false});
         ViewBag.ItemList = ItemList;

查看

<table>
      @foreach (var item in ViewBag.ItemList)
           {
            <tr><td>
           <input type= "checkbox" id = "Check_@item.ItemID" checked="@item.IsAvailable" 
           onclick="CheckOnlyOneCheckBox(this);"/>
           <label for="Check_@item.ItemID">@item.ItemName</label>
           </tr>
           }
 </table>

遇到了2个主要问题:

(a) 无法使用 submit button 检索到 selected box 的值

   foreach (var item in ViewBag.ItemList)
         {
           if (item.IsCheck)
              {
                var zz = item.ItemName;
               }                     
          }     

(b) 使用&lt;input type= "checkbox"&gt; 显示的ItemName 的格式看起来与使用@Html.CheckBoxFor 从先前的checkbox list 获得的格式略有不同(例如粗体)。

因此,在使用 @Html.CheckBoxForViewBag 方面的任何帮助将不胜感激。

编辑

@Md Farid Uddin Kiron

主要问题在于 checkbox 列表已经通过以下方式定义(在同一个 View 中):

List<test> chk = new List<test>();
          chk.Add(new test() {ReferalTypeId=1, ReferalTypeName = "box1",
IsReferalCheck=false});
          chk.Add(new test() {ReferalTypeId=2, ReferalTypeName = 
"box2", IsReferalCheck=false});
          chk.Add(new test() {ReferalTypeId=3, ReferalTypeName = 
"Other", IsReferalCheck=false});

 CtrList chklist = new CtrList(); // Ctrl being a public class defined 
                                 // in MODEL
 chklist.reflist = chk;  
 return View(chklist);

根据经验,我最终遇到了一种情况,我无法在 public IActionResult Index() 中定义另一个 checkbox 列表返回除 chklist 以外的其他内容,因为在循环时不会定义变量(例如 list)它来自View

因此,我不得不使用:ViewBag,使我能够毫无问题地将变量从Model 传递到View。如果没有 binding 它,这种有效的解决方法会引发另一个问题,我正在调查的最后解决方案包括:

(a)looping 通过checkbox

(b) 通过ViewBag 识别所选值;

(c) 然后找到一种方法将选定的变量从View 传递给Controller。但是,我不得不承认,后一种方法看起来并不理想。

最好的

【问题讨论】:

  • 你为什么不尝试使用@model List&lt;Test&gt; 而不是ViewBag.ItemList 这里viewBag 的任何具体原因
  • @dark.vador 你能分享一下cshtml的代码吗?
  • 到目前为止,我已经对其进行了研究,您可以使用 ViewBag 处理单个复选框的 CheckBoxFor 助手,但对于助手的复选框列表,您会遇到许多其他问题。第一个问题是在将值提交给控制器时,您不能轻松地将值与它绑定。如果您想尝试,请告诉我。有更好的解决方案使用viewModel
  • @MdFaridUddinKiron:非常感谢您的回复。我已经根据问题编辑了帖子,同时对了解最佳方法很感兴趣。最好的。
  • @Rahatur:感谢您的反馈。由于cshtml 相当庞大,我已经编辑了帖子,希望它有助于准确理解遇到的问题。最佳

标签: c# asp.net-mvc asp.net-core razor-pages html-helper


【解决方案1】:

我对您的方案进行了很多研究。您计划的方式无法很好地执行,因为我们无法在CheckBoxFor 上设置htmlAttributes,因此我们无法从CheckBoxFor 中检索值,因为您可能知道要从提交的项目中获取值,我们需要设置htmlAttributes就像id classname 一样在上面

因此,考虑到您的情况,我为您建立的最简单的解决方案如下:

您的预定义模型:

public class CheckBoxTestModel
    {
        public int ItemID { get; set; }
        public string ItemName { get; set; }
        public bool IsAvailable { get; set; }
    }

查看模型以引导查看查看:

 public class CheckBoxFromViewBagModel
    {
        public List<CheckBoxTestModel> CheckBoxes { get; set; }
        
    }

控制器加载:

 public IActionResult CheckboxforFromViewBag()
        {
            var checkBoxList = new List<CheckBoxTestModel>()
            {
                new CheckBoxTestModel() { ItemID=1,ItemName="apple", IsAvailable = false },
                new CheckBoxTestModel() { ItemID=2,ItemName="mango", IsAvailable = false },
                new CheckBoxTestModel() { ItemID=3,ItemName="stuck", IsAvailable = false },
                new CheckBoxTestModel() { ItemID=4,ItemName="blocked", IsAvailable = false },
                new CheckBoxTestModel() { ItemID=5,ItemName="help:(", IsAvailable = false },


            };

            var model = new CheckBoxFromViewBagModel();
            model.CheckBoxes = checkBoxList;
            return View(model);
        }

加载复选框时查看:

@model CheckBoxFromViewBagModel
@{
    ViewData["Title"] = "CheckboxforFromViewBag";
}
<h4>Load CheckBox From ViewModel & Submit value to Controller wtih Selected Value</h4>

<hr />
<style>
    table {
        font-family: arial, sans-serif;
        border-collapse: collapse;
        width: 100%;
    }

    td, th {
        border: 1px solid #dddddd;
        text-align: left;
        padding: 8px;
    }
</style>
@using (Html.BeginForm("SubmitValueFromCheckBoxList", "UserLog"))
{
    <table class="table-bordered">
        <tr>
            <th>Item Name</th>
            <th>Is Checked</th>

        </tr>

        @for (int i = 0; i < Model.CheckBoxes.Count; i++)
        {
            <tr>

                <td> @Model.CheckBoxes[i].ItemName</td>
                <td> @Html.CheckBoxFor(r => Model.CheckBoxes[i].IsAvailable)</td>
                @Html.HiddenFor(h => @Model.CheckBoxes[i].ItemID)
                @Html.HiddenFor(h => @Model.CheckBoxes[i].ItemName)

            </tr>

        }
    </table>
    <br />
    <input id="Button" type="submit" value="Submit To Controller" class="btn btn-primary" />
}

控制器提交值时:

        [HttpPost]
        public IActionResult SubmitValueFromCheckBoxList(CheckBoxFromViewBagModel checkBoxViewModel)
        {
            var checkBoxValueFromView = checkBoxViewModel;
            return Ok(checkBoxValueFromView);
        }

输出:

注意:根据您的情况,我认为这是处理此问题的优雅方式。除了周围的任何工作给我们带来另一个 挑战。在我的解决方案中,您可以忽略 CSS 部分。这里重要和棘手的部分是@Html.HiddenFor(h =&gt; @Model.CheckBoxes[i].ItemID) @Html.HiddenFor(h =&gt; @Model.CheckBoxes[i].ItemName) 为我们设置了htmlAttributes

希望对你有帮助。

【讨论】:

  • 非常感谢您花时间写这篇文章。此外,解释非常清楚。非常感谢,因此我很感激。最好的问候。
  • 很高兴调查您的问题。
猜你喜欢
  • 1970-01-01
  • 2011-02-05
  • 2018-08-22
  • 1970-01-01
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2013-08-04
相关资源
最近更新 更多