MVC3中的CheckboxList视图并获取传递给控制器​​的选中项

发布于 2024-10-21 18:45:05 字数 260 浏览 1 评论 0原文

我有一个 MoreInfo 类:

public class MoreInfo
{
        public string Name { get; set; }
        public string selectedCheckboxItems {get; set;}
}

我想知道如何在视图上创建一个复选框列表,并在提交时将选中的项目传递给我的控制器。

我将如何创建复选框列表以及如何传递所有选中的项目并处理它们?

I have a class for MoreInfo:

public class MoreInfo
{
        public string Name { get; set; }
        public string selectedCheckboxItems {get; set;}
}

I want to know how to create a checkbox list on the view and pass the checked off items to my controller on submit.

How would I go about creating the checkbox list and how to pass all the checked items and process them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

余罪 2024-10-28 18:45:05

让我们稍微修改一下您的模型:

public class ItemViewModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public bool Checked { get; set; }
}

然后您可以有一个控制器:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        // This action is used to render the form => 
        // we should populate our model with some values
        // which could obviously come from some data source
        var model = new[]
        {
            new ItemViewModel { Id = "1", Checked = true, Name = "item 1" },
            new ItemViewModel { Id = "2", Checked = false, Name = "item 2" },
            new ItemViewModel { Id = "3", Checked = true, Name = "item 3" },
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<ItemViewModel> items)
    {
        // This action will be invoked when the form is submitted
        // and here the view model will be properly bound and
        // you will get a collection of all items with their
        // corresponding id, name and whether they were checked or not
        ...
    }
}

然后您将有一个相应的视图(~/Views/Home/Index.cshtml),其中包含允许用户检查/的表单取消选中值:

@model IEnumerable<AppName.Models.ItemViewModel>
@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <input type="submit" value="OK" />
}

最后是编辑器模板(~/Views/Home/EditorTemplates/ItemViewModel.cshtml):

@model AppName.Models.ItemViewModel
// Those two hidden fields are just to persist the id and name
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.Name)
<div>
    @Html.CheckBoxFor(x => x.Checked)
    @Html.LabelFor(x => x.Checked, Model.Name)
</div>

Let's modify your model a little:

public class ItemViewModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public bool Checked { get; set; }
}

then you could have a controller:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        // This action is used to render the form => 
        // we should populate our model with some values
        // which could obviously come from some data source
        var model = new[]
        {
            new ItemViewModel { Id = "1", Checked = true, Name = "item 1" },
            new ItemViewModel { Id = "2", Checked = false, Name = "item 2" },
            new ItemViewModel { Id = "3", Checked = true, Name = "item 3" },
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<ItemViewModel> items)
    {
        // This action will be invoked when the form is submitted
        // and here the view model will be properly bound and
        // you will get a collection of all items with their
        // corresponding id, name and whether they were checked or not
        ...
    }
}

then you would have a corresponding view (~/Views/Home/Index.cshtml) which would contain the form allowing the user to check/uncheck values:

@model IEnumerable<AppName.Models.ItemViewModel>
@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <input type="submit" value="OK" />
}

and finally the editor template (~/Views/Home/EditorTemplates/ItemViewModel.cshtml):

@model AppName.Models.ItemViewModel
// Those two hidden fields are just to persist the id and name
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.Name)
<div>
    @Html.CheckBoxFor(x => x.Checked)
    @Html.LabelFor(x => x.Checked, Model.Name)
</div>
奢望 2024-10-28 18:45:05
public class MoreInfo
{
        public Int64 Id {get; set;}
        public string Name { get; set; }
        public bool Checkbox {get; set;}
}

控制器操作:

public ActionResult Index(){
  var list = new List<MoreInfo>{
      new MoreInfo{Id = 1, Name = "Name1", Checkbox = false},
      new MoreInfo{Id = 2, Name = "Name2", Checkbox = false},
      new MoreInfo{Id = 3, Name = "Name3", Checkbox = true},
  };
  return View(list);
}

[HttpPost]
public ActionResult Index(List<MoreInfo> lists){

  return View(lists);
}

Razor 视图:

@model List<MoreInfo>

<form action="" method="POST">
@for (var i = 0; i < Model.Count();i++ )
{
    @Html.HiddenFor(it => it[i].Id)
    @Html.TextBoxFor(it => it[i].Name)
    @Html.CheckBoxFor(it => it[i].Checkbox)
}
<input type="submit" />
</form>

更多信息
此处

public class MoreInfo
{
        public Int64 Id {get; set;}
        public string Name { get; set; }
        public bool Checkbox {get; set;}
}

Controller Action:

public ActionResult Index(){
  var list = new List<MoreInfo>{
      new MoreInfo{Id = 1, Name = "Name1", Checkbox = false},
      new MoreInfo{Id = 2, Name = "Name2", Checkbox = false},
      new MoreInfo{Id = 3, Name = "Name3", Checkbox = true},
  };
  return View(list);
}

[HttpPost]
public ActionResult Index(List<MoreInfo> lists){

  return View(lists);
}

Razor View:

@model List<MoreInfo>

<form action="" method="POST">
@for (var i = 0; i < Model.Count();i++ )
{
    @Html.HiddenFor(it => it[i].Id)
    @Html.TextBoxFor(it => it[i].Name)
    @Html.CheckBoxFor(it => it[i].Checkbox)
}
<input type="submit" />
</form>

More information
here

隔纱相望 2024-10-28 18:45:05

就这么简单:
1. 创建带有字符串 id 和布尔值的复选框类。
2. 将复选框列表放入控制器方法中并指定名称。
3. 在视图中动态创建 2 个字段,但确保符合 Razor 引擎命名系统。

要创建动态复选框列表,您需要了解剃刀引擎的工作方式,
假设你有这个代码
在视图的头部,您包含一个像这样的模型:

@model MyProject.Site.Models.MyWebModel  

该模型有一个设置类,里面有一个 bool ,如下所示:

public class MyWebModel  
{  
    public HighchartsSettingModel Settings { get; set; }  
}  
public class HighchartsSettingModel  
{  
    public bool JoinSameType{ get; set; }  
}

在视图中,您有:

@Html.CheckBoxFor(x => x.Settings.JoinSameType)

简而言之,这将创建以下 html 代码:

<input data-val="true" data-val-required="The JoinSameType field is required." id="Settings_JoinSameType" name="Settings.JoinSameType" type="checkbox" value="true" />
<input name="Settings.JoinSameType" type="hidden" value="false" />

到目前为止,对于 CheckBoxFor 来说效果很好,这是框架的一部分,我们如何使用数组?


所以现在我们需要做的就是了解如何在控制器方法中使用列表,
假设你有这个类:

public class Checkbox{
   public string Id { get; set; }
   public bool Value { get; set; }
}

并且在控制器中你有这个:

public ActionResult SensorSearch(List<Checkbox> selectedSensors, string search, string subSearch, string page, string back)

视图将如下所示:

@{  
        int counter = 0;  
        string id_name, id_id, value_id, value_name;  
    }  
    @foreach (var item in Model.SensorList)  
    {  
        id_id = "selectedSensors_" + counter + "__Value";  
        id_name = "selectedSensors[" + counter + "].Value";  
        value_id = "selectedSensors_" + counter + "__Id";  
        value_name = "selectedSensors[" + counter + "].Id";  
        counter++; 


    <li><a href="#" style="padding-top: 0px;padding-bottom: 0px;padding-right: 42px;padding-left: 0px;">
        <label style="border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;" data-corners="false">
            <fieldset data-role="controlgroup" >
                <input id="@id_id" name="@id_name" type="checkbox" value="true" />
                <input id="@value_id" name="@value_name" type="hidden" value="@item.Key" />                                
                <label for="@id_id" style="border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;">
                    <label  style="padding:10px 0px 0px 10px;">
                        <h3>@item.Key</h3>
                        <p>User Name: @item.Value</p>
                    </label>
                </label>
            </fieldset>
        </label>
        </a><a href="#" rel="external"></a>
    </li>
}
</ul>   

不要忘记视图中的表单:

@using (Html.BeginForm("SensorSearch", "Home", Model.PageNav.StayRouteValues, FormMethod.Post, new Dictionary<string, object>() { { "data-ajax", "false" }, { "id", "sensor_search_form" } }))

现在呈现的页面在复选框方面将如下所示:

<li><a href="#" style="padding-top: 0px;padding-bottom: 0px;padding-right: 42px;padding-left: 0px;">
<label style="border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;" data-corners="false">
    <fieldset data-role="controlgroup" >
        <input id="selectedSensors_16__Value" name="selectedSensors[16].Value" type="checkbox" value="true" />
        <input id="selectedSensors_16__Id" name="selectedSensors[16].Id" type="hidden" value="10141" />                                
        <label for="selectedSensors_16__Value" style="border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;">
            <label  style="padding:10px 0px 0px 10px;">
                <h3>10141</h3>
                <p>User Name: 10141_TEN-2MP</p>
            </label>
        </label>
    </fieldset>
</label>
</a><a href="#" rel="external"></a>
</li>

你需要注意的是为输入复选框和输入隐藏指定的名称,我们使用它类似于剃刀引擎创建名称的方式,因此在提交后,引擎会将其呈现为数组,因此您可以在需要的地方创建任何动态复选框列表就像使用任何其他语言一样(例如 php 等...)。

就这么简单:
就这么简单:
1. 创建带有字符串 id 和布尔值的复选框类。
2. 将复选框列表放入控制器方法中并指定名称。
3. 在视图中动态创建 2 个字段,但确保符合 Razor 引擎命名系统。

我希望它有帮助。

its that easy:
1. create the checkbox class with string id and bool value.
2. put list of checkbox in the controller method with some name.
3. create 2 fields dynamically in your view but make sure you conform to the razor engine naming system.

to create a dynamic checkbox list you need to understand the way the razor engine works,
say you have this code
in the head of the view you include a model like so:

@model MyProject.Site.Models.MyWebModel  

that model has a setting class that has a bool inside like so:

public class MyWebModel  
{  
    public HighchartsSettingModel Settings { get; set; }  
}  
public class HighchartsSettingModel  
{  
    public bool JoinSameType{ get; set; }  
}

and in the view you have:

@Html.CheckBoxFor(x => x.Settings.JoinSameType)

in short this creates the following html code:

<input data-val="true" data-val-required="The JoinSameType field is required." id="Settings_JoinSameType" name="Settings.JoinSameType" type="checkbox" value="true" />
<input name="Settings.JoinSameType" type="hidden" value="false" />

so far so good for the CheckBoxFor, that is a part of the framwork, how do we work with arrays?


so now all we need to do is to understand how to work with list in a controller method,
say you have this class:

public class Checkbox{
   public string Id { get; set; }
   public bool Value { get; set; }
}

and in the controller you have this:

public ActionResult SensorSearch(List<Checkbox> selectedSensors, string search, string subSearch, string page, string back)

and the view will look like so:

@{  
        int counter = 0;  
        string id_name, id_id, value_id, value_name;  
    }  
    @foreach (var item in Model.SensorList)  
    {  
        id_id = "selectedSensors_" + counter + "__Value";  
        id_name = "selectedSensors[" + counter + "].Value";  
        value_id = "selectedSensors_" + counter + "__Id";  
        value_name = "selectedSensors[" + counter + "].Id";  
        counter++; 


    <li><a href="#" style="padding-top: 0px;padding-bottom: 0px;padding-right: 42px;padding-left: 0px;">
        <label style="border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;" data-corners="false">
            <fieldset data-role="controlgroup" >
                <input id="@id_id" name="@id_name" type="checkbox" value="true" />
                <input id="@value_id" name="@value_name" type="hidden" value="@item.Key" />                                
                <label for="@id_id" style="border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;">
                    <label  style="padding:10px 0px 0px 10px;">
                        <h3>@item.Key</h3>
                        <p>User Name: @item.Value</p>
                    </label>
                </label>
            </fieldset>
        </label>
        </a><a href="#" rel="external"></a>
    </li>
}
</ul>   

lets not forget the form in the view:

@using (Html.BeginForm("SensorSearch", "Home", Model.PageNav.StayRouteValues, FormMethod.Post, new Dictionary<string, object>() { { "data-ajax", "false" }, { "id", "sensor_search_form" } }))

now the rendered page will look like so in the checkbox aspect:

<li><a href="#" style="padding-top: 0px;padding-bottom: 0px;padding-right: 42px;padding-left: 0px;">
<label style="border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;" data-corners="false">
    <fieldset data-role="controlgroup" >
        <input id="selectedSensors_16__Value" name="selectedSensors[16].Value" type="checkbox" value="true" />
        <input id="selectedSensors_16__Id" name="selectedSensors[16].Id" type="hidden" value="10141" />                                
        <label for="selectedSensors_16__Value" style="border-top-width: 0px;margin-top: 0px;border-bottom-width: 0px;margin-bottom: 0px;border-left-width: 0px;border-right-width: 0px;">
            <label  style="padding:10px 0px 0px 10px;">
                <h3>10141</h3>
                <p>User Name: 10141_TEN-2MP</p>
            </label>
        </label>
    </fieldset>
</label>
</a><a href="#" rel="external"></a>
</li>

what you need to notice is the names given to the input-checkbox and the input-hidden we used it similar to the way razor engine creates name and so after submit the engine will render this as an array and so you can create any dynamic checkbox list where ever you want same as you would in any other language (say php and so...) .

its that easy:
its that easy:
1. create the checkbox class with string id and bool value.
2. put list of checkbox in the controller method with some name.
3. create 2 fields dynamically in your view but make sure you conform to the razor engine naming system.

i hoped it helped.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文