I want to use a CheckBoxList AND dropdownlist AND other html controls on ONE view (.cshtml) using ASP.NET MVC and C#.
The most current theme to my struggling project is this: when you want to save/edit the form, on top of the view you have this line:
@model WebApplication1.Models.tbl_hobbies
And then you can use your html helper/input code like such:
@Html.EditorFor(model => model.Name_and_Surname, new { htmlAttributes = new { @class = "form-control" } })
Most of the checkbox projects I've tried all have this, so that it can receive the list of objects using a foreach etc.
@model List<WebApplication1.Models.tbl_Hobbies>
And then the checkboxlist code:
@for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>
@Html.CheckBoxFor(m => m[i].isSelected)
</td>
<td>
@Html.DisplayFor(m => m[i].hobbyname)
@Html.HiddenFor(m => m[i].hobbyid)
</td>
</tr>
}
Can anyone show me how to combine the two methods on ONE view, or an example anywhere? I've searched and tried to implement most solutions but none is working. Please assist.
You can have one ViewModel
with two different properties, one of tbl_hobbies
and the other of List<tbl_hobbies>
. So it should look something like:
public class HobbiesViewModel
{
public tbl_hobbies Hobby { get; set; }
public List<tbl_hobbies> Hobbies { get; set; }
}
In your view (.cshtml
), you can use your ViewModel
as:
@model YourNameSpace.HobbiesViewModel
Now you can use EditorFor(..)
as:
@Html.EditorFor(model => model.Hobby.Name_and_Surname, new { htmlAttributes = new { @class = "form-control" } })
For your check boxes you can make use of foreach
loop as:
@foreach (var hobby in Model.Hobbies)
{
<tr>
<td>
@Html.CheckBoxFor(m => hobby.isSelected)
</td>
<td>
@Html.DisplayFor(m => hobby.hobbyname)
@Html.HiddenFor(m => hobby.hobbyid)
</td>
</tr>
}
Finally, in your controller action:
public ActionResult SomeAction()
{
var hobbiesViewModel = //get the relevant data for your view model.
return View(hobbiesViewModel);
}