But, how do you create the ViewData, i think no checkbox will be checked by default.
To have a checked/selected value, you should have something like this:
SelectList AvalCoursesList = new SelectList(AvalCourses.AsEnumerable(), "COURSE1", "COURSE_NAME", "SelectedValue"); // <-- change string.Empty with the default selected value
DivakarGanta
Member
39 Points
140 Posts
how to use ViewData to bind with checkboxs and default values.
Apr 17, 2012 08:33 AM|LINK
I have functionality as the below VieData["AvalCourses"] values will be bind to Check boxes with foreach.
SelectList AvalCoursesList = new SelectList(AvalCourses.AsEnumerable(), "COURSE1", "COURSE_NAME", string
.Empty);
ViewData[
"AvalCourses"] = AvalCoursesList;
@
foreach (SelectListItem item in (SelectList)ViewData["AvalCourses"
])
{
<tr
>
<td
>
<input type="checkbox" value = "@item.Value" name="@item.Value" class
="CourseCheckboxList"/>
</td
>
<td
>
@Html.DisplayFor(modelItem => item.Text)
</td
>
</tr
>
}
Please help me in the above code to some values will be defaultly checked when returns to View.
zuperboy90
Participant
977 Points
819 Posts
Re: how to use ViewData to bind with checkboxs and default values.
Apr 17, 2012 08:49 AM|LINK
Hello,
try this
@if(item.Selected) { <input type="checkbox" value = "@item.Value" checked="checked" name="@item.Value" class="CourseCheckboxList" /> } else { <input type="checkbox" value = "@item.Value" name="@item.Value" class="CourseCheckboxList" /> }But, how do you create the ViewData, i think no checkbox will be checked by default.
To have a checked/selected value, you should have something like this:
Bhavik Solu...
Member
746 Points
159 Posts
Re: how to use ViewData to bind with checkboxs and default values.
Apr 17, 2012 09:11 AM|LINK
Hi,
Controller code
List<SelectListItem> _LiList = new List<SelectListItem>(); AddItemInlist("1", "true", _LiList, false); AddItemInlist("2", "false", _LiList, false); AddItemInlist("3", "true", _LiList, false); AddItemInlist("4", "false", _LiList, false); ViewBag.Chklist = new SelectList(_LiList, "Value", "Text"); } public void AddItemInlist(string Key, string value, List<SelectListItem> addtolist, bool IsSelected) { SelectListItem Li = new SelectListItem(); Li.Text = Key; if (IsSelected) { Li.Selected = true; } Li.Value = value.ToString(); addtolist.Add(Li); }View part
@foreach (SelectListItem item in (SelectList)ViewBag.Chklist) { @Html.CheckBox(item.Text,Convert.ToBoolean(item.Value)); }Bhavik Solu...
Member
746 Points
159 Posts
Re: how to use ViewData to bind with checkboxs and default values.
Apr 23, 2012 10:02 AM|LINK
Hi Divakar,
Sorry i am in meeting when you call me. if you have any question or doubts. please ask me in forms so i will reply you when i am free
Regards,
Bhavik Solanki