Click here to Skip to main content
15,905,508 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My model is..

public class SubscribedService
	{
		public int ServiceId { get; set; }
		public string ServiceName { get; set; }
		public bool Subscribed { get; set; }
	}


	public class RegistrationModel
	{
		public RegistrationModel()
		{
			Services = new List<SubscribedService>();
			using (CommonSchemaContainer container = new CommonSchemaContainer())
			{
				var dbServices = container.Services.ToList();
				dbServices.ForEach(a =>
				{
					Services.Add(new SubscribedService()
					{
						ServiceId = a.ServiceId,
						ServiceName = a.ServiceName,
                        Subscribed = false
					});
				});
			}
		}
public List<SubscribedService> Services { get; set; }



View for the checkboxes is
@for (int i = 0; i < Model.Services.Count(); i++)
				{
					@Html.CheckBoxFor(m => m.Services.ElementAt(i).Subscribed, new { @id = "chk" + i.ToString() })
					@Html.HiddenFor(m => m.Services.ElementAt(i).ServiceId, new { @id = "hdn" + i.ToString() })
					@Html.DisplayFor(m => m.Services.ElementAt(i).ServiceName, new { @id = "lbl" + i.ToString() })
					<br />
				}


I need to get the selected checkboxes from the controller.But the "Subscribed" entity is always getting false.

Controller is..

foreach (SubscribedService ServiceEntity in model.Services)
                    {
                        if (ServiceEntity.Subscribed)
                        {
                            string str = ServiceEntity.ServiceName;
                        }
                    }


What I have tried:

Tried to get the property checked but always false.
Posted
Updated 13-Dec-17 3:24am

1 solution

Change your view to:
@for (int i = 0; i < Model.Services.Count; i++)
{
    @Html.CheckBoxFor(m => m.Services[i].Subscribed)
    @Html.HiddenFor(m => m.Services[i].ServiceId)
    @Html.HiddenFor(m => m.Services[i].ServiceName)
    @Html.DisplayFor(m => m.Services[i].ServiceName)
    <br />
}

You need to use the indexer ([i]) rather than the ElementAt method.

You'll also need to add a hidden field to pass the service name back to the controller.

You might also need to move the initialization out of the RegistrationModel constructor, since that will also be called when the posted values are being loaded.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900