【问题标题】:Persist checkbox values on postback in MVC3在 MVC3 中回发时保留复选框值
【发布时间】:2013-05-14 03:07:07
【问题描述】:

型号:

  public class UserViewModel
    {       
        public UserDetail user { get; set; }
        public List<int> SelectedRoles { get; set; }     
    }

HttpGet 操作:

   public ActionResult Index()
   {
        ViewBag.Roles = list of roles (List<Roles>)
        return View();
   }

查看:

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{      

    foreach (var item in ViewBag.Roles)
    {

      <input id="SelectedRoles" name="SelectedRoles" type="checkbox" value="@item.Id" >         
      @item.Name
    } 

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

HttpPost 操作:

 [HttpPost]
  public ActionResult CreateUser(UserViewModel model, FormCollection form)
  {
     foreach (int roleId in model.SelectedRoles)
     {

         Here I am getting IDs of SelectedRoles as roleId
     }
  }

在 HttpPost 上,我想保留我选择的复选框值。在 MVC3 中如何实现?

【问题讨论】:

    标签: asp.net-mvc checkbox http-post


    【解决方案1】:

    看起来复选框绑定到 ViewBag 上的属性。您必须在 post action 中重新分配 ViewBag 上的角色,以便在 post action 执行后呈现视图时可以反弹 UI。 viewbag 不会在不同的视图渲染之间持续存在,所以必须重置它

    【讨论】:

      猜你喜欢
      • 2012-01-06
      • 2012-03-27
      • 2013-01-20
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多