0

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.

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a mil @Izzy . :)

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.