I am new to asp.net mvc. I am making an online video store application.
I have this view:
where users can choose which videos their gonna rent. The cod
Looks like a great use case to make use of Editor Templates.
Create a view model like this for your view.
public class RentVideoVM
{
public List<VideoSelection> Videos { set; get; }
//Add other properties needed for your view.
}
public class VideoSelection
{
public int VideoId { set; get; }
public string Name { set; get; }
public bool IsSelected { set; get; }
//Add other properties needed for your view.
}
The IsSelected
property of VideoSelection
class is used to store users selection on the check box from the UI.
Now in your GET action method, create an instance of the RentVideoVM
viewmodel, Load the Videos collection and send it to the view,
public ActionResult Register()
{
var vm = new RentVideoVM();
vm.Videos = db.Videos.Select(s => new VideoSelection
{
VideoId = s.VideoId,
Name = s.VideoName
}).ToList();
return View(vm);
}
Change it db.YourWhateverDBSet
instead of db.Videos
Now we need to create an editor template. Go to Views
folder and go inside the folder for your current controller and create a sub folder called "EditorTemplates". Add a new view there with the name VideoSelection.cshtml
and have the below code there.
@model YourNamespace.VideoSelection
<div>
@Model.Name
@Html.CheckBoxFor(d=>d.IsSelected)
@Html.HiddenFor(s => s.VideoId)
</div>
You may change the html markup however you want. Make it fancy !
Now in your main view, which is bound to our RentVideoVM
view model , call the Html.EditorFor
helper method to render the Videos with checkboxes.
@model YourNamespace.RentVideoVM
@using (Html.BeginForm())
{
@Html.EditorFor(s=>s.Videos)
<input type="submit"/>
}
And your HttpPost
action to handle the form posting would be
[HttpPost]
public ActionResult Register(RentVideoVM model)
{
//check model.Videos collection
// to do : Save and redirect
// If something wrong happened, reload Videos collection
return View(model);
}
When user posts the form, you can inspect the Videos
collection of the posted model. IsSelected
property will be true for those videos which user checked.
you may want to build a view model
public class YourDBContext
{
public int Id { get; set; }
public string Name { get; set; }
}
public class YourDBContextView
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
and use @using (Html.BeginForm()) on the view
[HttpPost]
public ActionResult Index(IEnumerable<YourDBContextView> obj)
{
//You can get your checkbox here
foreach(YourDBContextView view in obj)
{
bool test = view.IsSelected;
}
}