如何在mvc3中的Controller中访问动态创建的复选框值?

时间:2013-01-23 12:40:45

标签: c# asp.net-mvc asp.net-mvc-3

我的视图包含复选框和提交按钮,如下所示。

@using (Html.BeginForm())
    {
        <fieldset>
            <legend style="font-size: 100%; font-weight: normal">Delete</legend>
            <p> Are you sure you want to delete?</p>
            @foreach (string resource in resources)
            {
                if (resource != "")
                {
                    <input type="checkbox" name="Resources" title="@resource" value="@resource" checked="checked"/>@resource
                    <br />
                }
            }
            <br />

            @Html.HiddenFor(m => m.AttendeeListString)
        @Html.HiddenFor(m => m.ResourceListString)

            <span class="desc-text">
                <input type="submit" value="Yes" id="btnYes" />
            </span>
            <span class="desc-text">
                <input type="submit" value="No" id="btnNo" />
            </span>
        </fieldset>
    }

以下是控制器代码......

public ActionResult DeleteResource(RoomModel roomModel)
{
...
}

RoomModel包含一些其他数据......

现在我如何访问控制器中的复选框值? 注意:当我点击提交按钮时,我有更多需要发送给Controller的信息......任何人都可以建议一些解决方案....

答案:

我已将这两个属性添加到我的模型

public List<SelectListItem> Resources
{
    get;
    set;
}

public string[] **SelectedResource**
{
    get;
    set;
}

我的视图复选框已更新如下

@foreach (var item in Model.Resources)
{
<input type="checkbox" name="**SelectedResource**" title="@item.Text" value="@item.Value" checked="checked"/>@item.Text
<br /><br />
}

在控制器......

if (roomModel.SelectedResource != null)
{
    foreach (string room in roomModel.**SelectedResource**)
    {
      resourceList.Add(room);
    }
}

注意:模型中的复选框名称和Property应该相同。就我而言,它是 SelectedResource

5 个答案:

答案 0 :(得分:1)

您有几个选择。最简单的是:

1)参数使用Resources属性绑定视图模型。我推荐这种方式,因为它是首选的MVC范例,您只需为需要捕获的任何其他字段添加属性(并且只需添加属性即可轻松利用验证)。

定义新的视图模型:

public class MyViewModel
{
    public MyViewModel()
    {
       Resources = new List<string>();
    }

    public List<string> Resources { get; set; }

    // add properties for any additional fields you want to display and capture
}

在控制器中创建操作:

public ActionResult Submit(MyViewModel model)
{
      if (ModelState.IsValid)
      {
           // model.Resources will contain selected values
      }
      return View();   
}

2)参数直接在动作中绑定名为resources的字符串列表:

public ActionResult Submit(List<string> resources)
{
      // resources will contain selected values

      return View();   

}

重要的是要注意,在这个问题中,视图是创建复选框,它将发送所有已检查资源的字符串值,而不是布尔值(如果您使用@Html.CheckBox帮助器,可能会如此)项目是否被检查。这很好,我只是指出为什么我的答案不同。

答案 1 :(得分:0)

在MVC操作中,有一个与复选框名称对应的参数,如:

bool resources
bool[] resources

答案 2 :(得分:0)

使用javascript或jquery收集所有值并发布到控制器

var valuesToSend='';

$('input:checked').each(function(){
valuesToSend+=$(this).val() + "$";//assuming you are passing number or replace with your logic.
});

并在提交后调用ajax函数

$.ajax({
url:'yourController/Action',
data:valuesTosend,
dataType:'json',
success:function(data){//dosomething with returndata}
})

或者您可以将模型传递给控制器​​。如果您实现了Model -View-ViewModel模式。

public class yourViewModel
{
    public string Id { get; set; }
    public bool Checked { get; set; }
}

行动方法

[HttpPost]
    public ActionResult Index(IEnumerable<yourViewModel> items)
    {
         if(ModelState.IsValid)
          {
            //do with items. (model is passed to the action, when you submit)
          }
    } 

答案 3 :(得分:0)

我假设resources变量是在Controller中生成的,或者可以放在ViewModel上。如果是这样,那么这就是我接近它的方式:

您的视图模型会添加一个Resources字典,看起来像这样:

public class RoomModel
{
    public Dictionary<string,bool> Resources { get; set; }

    // other values...
}

使用资源项的名称作为键(Resources)填充string词典,并将“已检查”值(bool)设置为默认状态false。

e.g。 (在你的[HttpGet]控制器中)

// assuming that `resource` is your original string list of resources
string [] resource = GetResources();
model.Resources = new Dictionary<string, bool>();
foreach(string resource in resources)
{
  model.Resources.Add(resource, false);
}   

要在视图中渲染,请执行以下操作:

@foreach (string key in Model.Resources.Keys)
{
  <li>
    @Html.CheckBoxFor(r => r.Resources[key])
    @Html.LabelFor(r => r.Resources[key], key)
  </li>
}

然后,这将使[HttpPost]控制器在您回发时自动将字典填充到模型上:

public ActionResult DeleteResource(RoomModel roomModel)
{
  // process checkbox values
  foreach(var checkbox in roomModel.Resources)
  {
    // grab values
    string resource = checkbox.Key;
    bool isResourceChecked = checkbox.Value;

    //process values...
    if(isResourceChecked)
    {
      // delete the resource
    }

    // do other things...
  }
}

答案 4 :(得分:0)

我已将这两个属性添加到我的模型

public List<SelectListItem> Resources
{
    get;
    set;
}

public string[] **SelectedResource**
{
    get;
    set;
}

我的视图复选框已更新如下

@foreach (var item in Model.Resources)
{
<input type="checkbox" name="**SelectedResource**" title="@item.Text" value="@item.Value" checked="checked"/>@item.Text
<br /><br />
}

在控制器......

if (roomModel.SelectedResource != null)
{
    foreach (string room in roomModel.**SelectedResource**)
    {
      resourceList.Add(room);
    }
}

注意:模型中的复选框名称和Property应该相同。在我的例子中,它是SelectedResource