Naren Gokal
Naren Gokal

Reputation: 117

checkbox values back to controller using htmlhelpers

I have the below code in my VIEW, and thereafter a submit button. I do have many of these checkboxes in my view, so that the user can click on as many as he wishes.

@Html.CheckBox("code" + l_code, false, new { Value = @item.expertiseCode })

In my controller i have the fll., which is the HTTPPost method

public ActionResult RegisterSP(RegisterModel model, FormCollection collection)

However, when debugging, i see that ALL the checkboxes are being passed back to the controller, and not just the ones that were clicked on. I just want the ones that were clicked on and ignore the rest for i need to add these to the DB. Also, the checbox values passed in contains TRUE/FALSE. Because of this the false value is also being added to the DB. If i use the below method (not using the htmlHelper), i dont have the above problem. But i wud like to use the htmlHelper:

<input type="checkbox" name="code@(l_code)" value="@item.expertiseCode" />

Upvotes: 1

Views: 3711

Answers (2)

Mediator
Mediator

Reputation: 15378

Try

@Html.CheckBox("code" + l_code, false, new { @value = item.expertiseCode })

or

string name = "code" + l_code;
@Html.CheckBox(name, false, new { @value = item.expertiseCode })

Upvotes: 0

Shyju
Shyju

Reputation: 218732

IF you have a collection of Checkboxes, Create a ViewModel like this

public class ExpertiseCodeViewModel 
{
  public string Name { set;get;}
  public int ExpertiseId { set;get;}
  public bool IsSelected { set;get;}
}

Now In your main ViewModel, Add a collection of this as a property

public class UserViewModel
{
  public List<ExpertiseCodeViewModel > Expertises{ set; get; }

  public UserViewModel()
  {
    if(this.Expertises==null)
       this.Expertises=new List<ExpertiseCodeViewModel>();
  }
}

And in your create an editor template called ExpertiseCodeViewModel

@model ExpertiseCodeViewModel 
@Html.CheckBoxFor(x => x.IsSelected)
@Html.LabelFor(x => x.IsSelected, Model.Name)
@Html.HiddenFor(x => x.ExpertiseId )

Include this in your Main View

@model UserViewModel
@using (Html.BeginForm())
{
  //other elements
 @Html.EditorFor(m=>m.Expertises)
 <input type="submit" value="Save" />
}

In your HTTPPost Action method,

[HttpPost]
public ActionResult Save(UserViewModel model)
{
  List<int> items=new List<int>();
   foreach (ExpertiseCodeViewModel objItem in model.Expertises)
   {
     if (objPVM.IsSelected)
     {
       //you can get the selected item id here
       items.Add(objItem.ExpertiseId);

     }
   } 
}

Upvotes: 1

Related Questions