Adding features while creating User in mvc using checkbox

前端 未结 2 1940
傲寒
傲寒 2021-01-25 15:17

i want to create users with special features in mvc. when user is going to create i want to assign some special feature to each user like particular user having his own house, h

2条回答
  •  走了就别回头了
    2021-01-25 15:51

    Use view models to represent what you display and edit

    public class FeatureVM
    {
      public int ID { get; set; }
      public string Name { get; set; }
      public bool IsSelected { get; set; }
    }
    
    public class UserVM
    {
      public string Name { get; set; }
      public string Address { get; set; }
      public List Features { get; set; }
    }
    

    Controller

    public ActionResult Create()
    {
      UserVM model = new UserVM();
      model.Features = // map all available features
      return View(model);
    }
    
    [HttpPost]
    public ActionResult Create(UserVM model)
    {
    
    }
    

    View

    @model UserVM
    @using(Html.BeginForm())
    {
      @Html.LabelFor(m => m.Name)
      @Html.TextBoxFor(m => m.Name)
      @Html.ValidationMessageFor(m => m.Name)
      .....
      for(int i = 0; i < Model.Features.Count; i++)
      {
        @Html.HiddenFor(m => m.Features[i].ID)
        @Html.CheckBoxFor(m => m.Features[i].IsSelected)
        @Html.LabelFor(m => m.Features[i].IsSelected, Model.Features[i].Name)
      }
      
    }
    

提交回复
热议问题