【问题标题】:How to access dynamically created checkbox value in Controller in mvc3?如何在 mvc3 的控制器中访问动态创建的复选框值?
【发布时间】:2013-01-23 12:40:44
【问题描述】:

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

@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 包含一些其他数据...

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

答案:

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

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);
    }
}

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

【问题讨论】:

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


【解决方案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) 参数直接在action中绑定一个名为resources的字符串列表:

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

      return View();   

}

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

【讨论】:

    【解决方案2】:

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

    bool resources
    bool[] resources
    

    【讨论】:

      【解决方案3】:

      使用 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)
                }
          } 
      

      【讨论】:

        【解决方案4】:

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

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

        public class RoomModel
        {
            public Dictionary<string,bool> Resources { get; set; }
        
            // other values...
        }
        

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

        例如(在您的 [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...
          }
        }
        

        【讨论】:

          【解决方案5】:

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

          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);
              }
          }
          

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-10-20
            • 1970-01-01
            • 2012-10-25
            • 1970-01-01
            • 2014-10-29
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多