1

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" />
1
  • How are your checkboxes created? Commented May 11, 2012 at 10:08

2 Answers 2

1

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

     }
   } 
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.