【问题标题】:MVC3 - How to correctly use @html.checkbox?MVC3 - 如何正确使用@html.checkbox?
【发布时间】:2012-04-09 12:34:53
【问题描述】:

我是 MVC3 的新手,我不知道如何在 MVC 中使用复选框。 我的视图中有一堆文本,例如

text1
text2
text3
text4
text5

submitbutton

此文本与任何模型无关,它只是纯文本。我想为每个项目放置一个复选框并将其链接到控制器,以便当用户选择一些复选框值并单击提交按钮时,我的控制器会选择已选择的项目。 我尝试使用 @html.checkbox("text"+ index) 并尝试将控制器设为

[HttpPost]
public ActionResult controller(List<string> list)
{
}

但这并没有选择所选项目的列表。你能告诉我我做错了什么或其他方法吗?

【问题讨论】:

  • 您应该创建一个将布尔属性和字符串属性关联起来的 ViewModel。 ViewModel 是你的朋友。

标签: asp.net-mvc asp.net-mvc-3 checkbox


【解决方案1】:

在这种情况下我会做的是让这些项目成为我的 ViewModel 的属性。

public class MyViewModel
{
  public bool text1  { set;get}
  public bool text2 { set;get;}
  public bool SomeMeaningFullName { set;get;}
  // Other properties for the view
}

在我的 Get Action 方法中,我会将这个 ViewModel 返回到我的视图

public ActionResult Edit()
{
  MyViewModel objVM=new MyViewModel();
  return View(objVM);
}

在我看来

@model MyViewModel

@using (Html.BeginForm("Edit","yourcontroller"))
{
  @Html.LabelFor(Model.text1)
  @Html.CheckBoxFor(Model.text1)
  @Html.LabelFor(Model.text2)
  @Html.CheckBoxFor(Model.text2)

  <input type="submit" value="Save" />
}

现在这个属性值将在你的 post action 方法中可用

[HttpPost]
public ActionResult Edit(MyViewModel objVM)
{
 //Here you can access the properties of objVM and do whatever

}

【讨论】:

    【解决方案2】:

    使用您的所有值创建一个 ViewModel。填充 ViewModel 并将其发送到视图。选中某些内容后,您就会知道帖子上的内容。

    public class MyModelViewModel
    {
        public List<CheckBoxes> CheckBoxList {get; set;} 
        // etc
    }
    
    public class CheckBoxes
    {
        public string Text {get; set;} 
        public bool Checked {get; set;}         
    }
    
    [HttpPost]
    public ActionResult controller(MyModelViewModel model)
    {
        foreach(var item in model.CheckBoxList)
        {
            if(item.Checked)
            {
                // do something with item.Text
            }
        }
    }
    

    基本上,ViewModel 是您的朋友。您希望每个 View 都有一个单独的 ViewModel,它是在 Controller 和 View 之间来回传递的。然后,您可以在控制器中或(最好)在服务层中进行数据解析。

    其他参考:
    Should ViewModels be used in every single View using MVC?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 2013-05-29
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多