Reputation: 451
I have a form, in my form user can fill their details and choose their interests that is in checkbox. I place interest section in a form as a partial view.
Form having,
I have a model that having all fields Name, BirthDay, Place. And another model for LookingFormodel.
Now when i submit form. all fields like name, Birthday and palce is comming to model but i am not getting checkbox selected item list.
How can i get checkbox values in form submit?
Upvotes: 1
Views: 7344
Reputation: 1038710
This seems like a good candidate for editor templates. As always we start by designing a view model:
public class MyViewModel
{
public string Name { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? DateOfBirth { get; set; }
public string Place { get; set; }
public IEnumerable<InterestViewModel> Interests { get; set; }
}
public class InterestViewModel
{
public int Id { get; set; }
public string InterestLabel { get; set; }
public bool IsSelected { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Name = "john",
DateOfBirth = new DateTime(1990, 1, 1),
Place = "Spain",
Interests = new[]
{
new InterestViewModel { Id = 1, InterestLabel = "cinema" },
new InterestViewModel { Id = 2, InterestLabel = "sport" },
new InterestViewModel { Id = 3, InterestLabel = "books" },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// TODO: process the results here, the view model will be
// correctly bound
....
}
}
then a view (~/Views/Home/Index.cshtml
)
@model MyViewModel
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.Name)
@Html.EditorFor(x => x.Name)
</div>
<div>
@Html.LabelFor(x => x.DateOfBirth)
@Html.EditorFor(x => x.DateOfBirth)
</div>
<div>
@Html.LabelFor(x => x.Place)
@Html.EditorFor(x => x.Place)
</div>
<h2>Interests</h2>
@Html.EditorFor(x => x.Interests)
<button type="submit">OK</button>
}
and a corresponding editor template which will be rendered for each element of the Interests collection (~/Views/Home/EditorTemplates/InterestViewModel.cshtml
):
@model InterestViewModel
@Html.LabelFor(x => x.IsSelected, Model.InterestLabel)
@Html.CheckBoxFor(x => x.IsSelected)
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.InterestLabel)
Upvotes: 4