I have a view:
#using(Html.BeginForm())
{
<div>
<table id="dimensionFeedbackTable">
<tbody>
#for(int i = 0; i < 6; i++)
{
<tr>
<td>
<div>
<p>
<text>
Rate #i
</text>
</p>
</div>
</td>
#foreach(var item in Model.DeptList)
{
<td>
<div style="text-align: center;">
#Html.RadioButtonFor(m => item.DepartmentValue, i,
new
{
id = i,
style = "min-height:45px;"
})
</div>
</td>
}
</tr>
}
</tbody>
</table>
<button id="submitComment" value="submit">
#{
<text>Submit</text>
}
</button>
</div>
}
Model in that view is EmployeeModelClass. Here it is:
public class EmployeeModelClass
{
public int Id
{
get; set;
}
public IEnumerable<DepartmentModelClass> DeptList
{
get; set;
}
}
public class DepartmentModelClass
{
public string DepartmentCode
{
get; set;
}
[Range(1, 6)]
public int? DepartmentValue
{
get; set;
}
}
My controller:
[HttpPost]
public ActionResult Index(EmployeeModelClass emp, IEnumerable<DepartmentModelClass> qec)
{
emp.DeptList = qec;
return View(emp);
}
I am trying to accomplish next:
Each row should be group for it self. For example Rate 1 row can have only one radio button selected. Now, these buttons should be bound. If second radio button is selected in any row then its value (DepartmentValue) should be set to 2. So when I submit, I get a collection of which radio buttons are selected.
I've tried a lot of combinations with setting proper model and binding it. Also tried html helper method RadioButton, but still no luck to return the values. Closest that I managed to get is returning a collection but although radio buttons are selected in Controller, collection is not null but values (DepartmentValues) are null.
Also, there are similar answers here but for some reason none of them is working for me. Any help and pointing direction are appreciated. Losing my mind over a simple thing.
One more thing, I tried with creating partials view but still now luck. I read online that is a bad practice to place for/foreach loop in a view and tried to simplify it but this approach is also not working.
Thanks
I notice few issues -
for loop and foreach loop are opposite.
Should use for for array of controls instead of foreach
Do not explicitly assign id to radio buttons new { id = i, ...})
View
#model DemoMvc.Models.EmployeeViewModel
#using (Html.BeginForm())
{
<div>
<table id="dimensionFeedbackTable">
<tbody>
#for (int i = 0; i < Model.DepartmentViewModels.Count; i++){
<tr>
<td>
<div>
<p>
<text>
Rate #Model.DepartmentViewModels[i].DepartmentCode
</text>
</p>
</div>
</td>
#for (int j = 1; j <= 6; j++)
{
<td>
<div style="text-align: center;">
#Html.RadioButtonFor(m =>
Model.DepartmentViewModels[i].DepartmentValue,
j, new { style = "min-height:45px;" })
#j
</div>
</td>
}
</tr>
}
</tbody>
</table>
<button id="submitComment" value="submit">Submit</button>
</div>
}
Model
public class EmployeeViewModel
{
public int Id { get; set; }
public IList<DepartmentViewModel> DepartmentViewModels { get; set; }
}
public class DepartmentViewModel
{
public string DepartmentCode { get; set; }
public int? DepartmentValue { get; set; }
}
Controller
public ActionResult Index()
{
// This could come from database.
var model = new EmployeeViewModel
{
DepartmentViewModels = new List<DepartmentViewModel>
{
new DepartmentViewModel{ DepartmentCode = "ABC", DepartmentValue = 1},
new DepartmentViewModel{ DepartmentCode = "DEF", DepartmentValue = 2},
new DepartmentViewModel{ DepartmentCode = "GHI", DepartmentValue = 3},
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(EmployeeViewModel model)
{
return View(model);
}
Result
Posted Value
Related
in my journey of learning ASP.NET MVC I encounterd another difficulty:
I'm trying to POST a form with 3 checkboxes, the checkboxes are looped onto the form according to a bound PresentationModel.
I don't know what to fill in at the "asp-for" tag-helpers for the checkboxes in the view so they pass a boolean to the "Create()" ActionResult in the controller and to show the values in the "Overview" View.
Currently it passes NULL for al of them, the other aproaches I tried always resulted in an "InvalidCastException" as it has to be a boolean not an "int[]".
PresentationModel (PMRegistration.cs)
public class PMRegistration
{
public List<Device> Devices { get; set; }
}
View (Index.cshtml)
#model Week3_oef2_ITPro.PresentationModel.PMRegistration
<form asp-controller="Register" asp-action="Create" method="post">
<table>
<tr>
<td>Are you wearing any dangerous accessoires</td>
</tr>
#foreach (var item in Model.Devices)
{
<tr>
<td>#item.Name</td>
<td class="form-group">
<input type="checkbox" asp-for="#item.CheckState" value="#item.Id" class="form-control" />
</td>
</tr>
}
<tr>
<td>
<input type="submit" class="btn btn-default" />
</td>
</tr>
</table>
</form>
Model (Device.cs)
public class Device
{
public int Id { get; set; }
public string Name { get; set; }
public bool CheckState { get; set; }
}
Model (Data.cs, the Device objects get initialized here)
private static List<Device> devices = new List<Device>();
static Data()
{
devices.Add(new Device() { Id = 1, Name = "Laptop" });
devices.Add(new Device() { Id = 2, Name = "Tablet" });
devices.Add(new Device() { Id = 3, Name = "Apple Watch" });
}
public static List<Device> GetDevices()
{
return devices;
}
Controller (RegisterController.cs)
public class RegisterController : Controller
{
// GET: /<controller>/
[HttpGet]
public IActionResult Index()
{
PMRegistration pm = new PMRegistration();
pm.Devices = Data.GetDevices();
return View(pm);
}
public ActionResult Create(PMRegistration pm)
{
if (ModelState.IsValid)
{
return View("Overview", pm);
}
else
{
return RedirectToAction("Index");
}
}
}
------------ SOLVED -------------
With HTML-helpers:
#for (int i = 0; i < Model.Devices.Count; i++)
{
<tr>
<td>
#Model.Devices[i].Name
</td>
<td>
#Html.CheckBoxFor(m => Model.Devices[i].CheckState)
#Html.HiddenFor(m => Model.Devices[i].Id)
#Html.HiddenFor(m => Model.Devices[i].Name)
</td>
</tr>
}
I am working on a project in dot Net + share-point,
In there controller get sharepoint list record & create a list of list object.
In view catch the object as one model and dilplay in a table.
Table view
enter image description here
Index.cshtml
#using( Html.BeginForm() )
{
<table id = "timeTrackingView" border="1" >
<tr>
<th>Projects</th>
#for (var date = #Model.Dates.AddDays(-(#Model.DateRange-1)); date <= #Model.Dates; date = date.AddDays(1))
{
<th >#date.Day/#date.Month/#date.Year</th>
}
</tr>
#{ double[] totalForToday = new double[#Model.DateRange];}
#for (int i = 0; i < #Model.TimeTrakings.Count; i++)
{
//var projectName = #Model.TimeTrakings[i][0].ProjectName;
int index = 0;
<tr>
<td>
#Model.TimeTrakings[i][0].ProjectName
</td>
#for (int j = 0; j < Model.TimeTrakings[i].Count(); j++)
{
totalForToday[index] = totalForToday[index] + #Model.TimeTrakings[i][j].Hours;
var time = #Html.EditorFor(model => #Model.TimeTrakings[i][j]);
<td>#time</td>
#*#Html.EditorFor(model => #Model.TimeTrakings[i][j].Hours)*#
index++;
}
</tr>
}
<tr>
<td>Total for day</td>
#foreach(var tot in totalForToday)
{
<td>#tot</td>
}
</tr>
</table>
<input type="submit" name="SubmitBtn"/>
}
I am trying to get table data into controller.. help me im my code only gettinh hours, need get project name date & hours together.
My controller.
[HttpPost]
public ActionResult Index(TimeTracking timeTracking)
{
////do the logic here
return View(this.ReceiveTimeTrackingData());
}
I Used two mode-:
Model1
public class TimeTrackingDetails
{
public string ProjectName { get; set; }
public DateTime Date { get; set; }
public double Hours { get; set; }
}
Model 2-:
public class TimeTracking
{
public List<List<TimeTrackingDetails>> TimeTrakings { get; set; }
}
If you need project name you should create an input. Now in your code you have just plain text with this line:
#Model.TimeTrakings[i][0].ProjectName
Just add another line onder it:
#Model.TimeTrakings[i][0].ProjectName
// this line will create additional hidden input and on form post it will be sended to server.
#Html.HiddenFor(x => x.TimeTrakings[i][0].ProjectName)
Not sure why I got down voted but I'm going to re-write my question after doing some research and testing. This is a side project that I'm using to learn MVC/EF/Repository/Bootstrap etc. I only get a couple hours here a few nights a week to work on it.
Basic original question:
I know I should really be using a List<> in a ViewModel to pass the data to the View but I'm not sure how or if it will meet my requirement.
What I am trying to do is get a list of users to display in a table which would have a checkbox in each row. Above that table I want to have a list of Groups to that they could be assigned to. You select the section from the DropDownList (DDL) and then check who you want to assign it to. It's the groups/sections that I want want to assign as a list and pass to the View.
So, I've got a ViewModel with a list and I'm using a repository to populate the VM. What I don't know how to do exactly is where/when to populate that list with each VM object and even if I do and there are say 50 users I wouldn't want to make 50 trips to the DB to pull the same information.That is why I'm thinking that for this scenario using the ViewBag to pass that Group list to the View might be justifiable. On the flip side I would like to learn how to populate that list properly in the VM for future coding.
Updated question/code:
So, after more research and following some suggestions I've now got the following code. I'm still not sure how I will properly populate my Patrols in my ViewModel in order to populate the DDL in my View.
At the moment I've got the View displaying the table with the checkboxes. Now I'm back to working on getting the values to populate the DDL and then I'll have to work on posting to the controller, looping to find the check rows, and updating the database. In my case each member record is defaulted to a PatrolId=0 and this page should allow me to update the PatrolId to a value from the DDL.
The Patrols property in the PatrolMemberViewModel should be a list of about 5 records that I would pull from a DB table instead of hard coding in the DDL.
ViewModel:
public class PatrolViewModel
{
public int PatrolId { get; set; }
public string PatrolName { get; set; }
}
public class PatrolMemberViewModel
{
[Key]
public int MemberId { get; set; }
public int PatrolId { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Phone")]
public string PhonePrimary { get; set; }
[Display(Name = "Email")]
public string EmailPrimary { get; set; }
public bool IsSelected { get; set; }
public PatrolViewModel Patrols { get; set; }
}
Controller:
public ViewResult Unassigned()
{
try
{
IEnumerable<PatrolMemberViewModel> model = repository.SelectAllUnassigned();
return View(model);
}
catch (Exception)
{
ModelState.AddModelError(string.Empty, "Error retrieving the record.");
return View();
}
}
Repository:
public IEnumerable<PatrolMemberViewModel> SelectAllUnassigned()
{
using (DataContext db = new DataContext())
{
var results = (from p in db.Person
where p.IsActive == true
&& p.IsScout == true
&& p.PatrolId == 0
select new PatrolMemberViewModel
{
MemberId = p.PID,
FirstName = p.FirstName ?? string.Empty,
LastName = p.LastName ?? string.Empty,
EmailPrimary = p.EmailPrimary ?? string.Empty,
PhonePrimary = p.PhonePrimary ?? string.Empty,
PatrolId = p.PatrolId,
IsSelected = false
}
).OrderBy(o => o.LastName).ThenBy(o => o.FirstName).ToList();
return results;
}
}
View:
#model IList<ProjectName.ViewModels.PatrolMemberViewModel>
#{
ViewBag.Title = "Unassigned";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Patrols</h2>
#using (Html.BeginForm("Update", "Patrol", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(false, "", new { #class = "alert alert-danger" })
<table class="table table-bordered table-striped table-hover table-condensed tbackground">
<tr>
<th class="text-center">
</th>
<th class="text-center">
First Name
</th>
<th class="text-center">
Last Name
</th>
<th class="text-center">
Email
</th>
<th class="text-center">
Phone
</th>
</tr>
#for (var i = 0; i < Model.Count(); i++)
{
<tr>
<td class="text-center">
#Html.CheckBoxFor(m => m[i].IsSelected)
</td>
<td>
#Html.DisplayFor(m => m[i].FirstName)
</td>
<td>
#Html.DisplayFor(m => m[i].LastName)
</td>
<td>
#Model[i].EmailPrimary
</td>
<td class="text-center">
#Html.DisplayFor(m => m[i].PhonePrimary)
</td>
</tr>
}
</table>
<div class="control-wrapper">
<input type="submit" id="btnSubmit" value="Assign" class="btn btn-success" />
</div>
}
<p> </p>
Start by creating the view models to represent what you want to display/edit in the view. Your PatrolMemberViewModel can be used but remove the [Key] attribute and the int PatrolId and PatrolViewModel Patrols properties.
Then create the parent view model
public class AssignPatrolViewModel
{
[Display(Name = "Patrol")]
[Required(ErrorMessage = "Please select a patrol")]
public int? SelectedPatrol { get; set; }
public IEnumerable<SelectListItem> PatrolList { get; set; }
public List<PatrolMemberViewModel> Members { get; set; }
}
and you GET method would be
public ViewResult Unassigned()
{
var model = new AssignPatrolViewModel
{
PatrolList = new SelectList(db.Patrols, "PatrolId", "PatrolName"), // modify to suit
Members = repository.SelectAllUnassigned().ToList()
};
return View(model);
}
and in the view
#model AssignPatrolViewModel
....
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.SelectedPatrol)
#Html.DropDownListFor(m => m.SelectedPatrol, Model.PatrolList, "Please select")
#Html.ValidationMessageFor(m => m.SelectedPatrol)
<table>
.... // thead elements
<tbody>
#for(int i = 0; i < Model.Members.Count; i++)
{
<tr>
<td>
#Html.CheckBoxFor(m => m.Members[i].IsSelected)
#Html.HiddenFor(m => m.Members[i].MemberId)
// add other hidden inputs for properties you want to post
</td>
<td>#Html.DisplayFor(m => m.Members[i].FirstName)</td>
....
</tr>
}
</tbody>
</table>
<input type="submit" value="Assign" class="btn btn-success" />
}
Then in the POST method
[HttpPost]
public ViewResult Unassigned(AssignPatrolViewModel model)
{
if (!ModelState.IsValid)
{
model.PatrolList = new SelectList(db.Patrols, "PatrolId", "PatrolName");
return View(model);
}
// Get selected ID's
IEnumerable<int> selected = model.Members.Where(m => m.IsSelected).Select(m => m.MemberId);
// Get matching data models
var members = db.Person.Where(p => selected.Contains(p.PID)); // modify to suit
// loop each each member, update its PatrolId to the value of model.SelectedPatrol
// save and redirect
}
You could create a new class for your view model, with the list of users and the list of sections as properties within it. Some people seem to like that approach.
But I think your use of ViewBag for passing the list of sections is perfectly valid. I do that all the time for DDLs like this.
I have a view with a list of items from a model. I need to add a checkbox to each row, have the user select multiple check boxes, and pass some identifier of what row was selected to the controller. I know how to pass a single value through an action link, but I'm not sure how to pass multiple values through an action link or how to "collect" which rows were selected. I'll show some of my code attempts below. Can someone help me sort out why I can't get the values of all the checkboxes passed to the controller?
Here's my page
Checkbox App ID Date Name
[] 1 5/10 Bob
[] 2 5/10 Ted
[] 3 5/11 Alice
What I need the user to do is select rows 1 & 3 (for example) and have those App ID's passed to the controller.
I started listing various attempts, but decided just to show my current attempt and see if anyone could point out what I'm doing wrong. The main difference I see between examples online and mine is that mine uses a PagedList and creates the rows of the table in a foreach loop.
The parameter ints is blank when it hits the controller. How do I get the values from the checkboxes into it? I used this site for the basic idea of naming all the checkboxes the same and passing a ICollection through the action link:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/
View:
#model PagedList.IPagedList<CarmelFinancialWeb.Models.ModelMerchantSummary>
<div class="block" style="width: 100%; float: left">
<p class="block-heading">
Merchant Application Report
</p>
<div class="table-holder">
<table class="table" style="margin-bottom: 0px">
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" name="ints" value=item.ApplicationID />
</td>
<td>
#Html.ActionLink(item.ApplicationID.ToString(), "ViewApplication", new { ID = item.ApplicationID, edit = 1 }, new AjaxOptions { HttpMethod = "GET" })
</td>
<td>
#Convert.ToDateTime(item.ApplicationDate).ToString("M/d/yy")
</td>
<td>
#item.ApplicantName
</td>
</tbody>
</table>
</div>
</div>
#Html.ActionLink("Print Application", "PrintApplication", "CreateContract", new { #class = "btn btn-primary" })
Controller:
[AuthorizeAdmin]
public ActionResult PrintApplication(ICollection<int> ints, string ID)
{
Contracts_Create contract = new Contracts_Create();
ModelApplication currentApplication = new ModelApplication();
currentApplication.contract = new ModelContract();
return File(contract.CreatePDF_PrintedApplication_English(currentApplication.contract.location, currentApplication.contract), "application/pdf");
}
Edit:
This got tagged as a duplicate of another question. The question there was about whether non-sequential input names could be used. My problem is that I'm using inputs that are not non-sequential, but it is still not working. I understand the concept, I just can't figure out why my specific code is not working. I've put a lot of time into this and can't find the answer to my specific code. Thanks!
Try passing a ViewModel into your page, and using the model binder to post the same view model back into your controller
Models:
public class MerchantModel
{
public int AppId { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class MerchantViewModel
{
public List<MerchantModel> Merchants { get; set; }
}
Controller:
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
var merchant1 = new MerchantModel
{
AppId = 1,
Name = "Bob"
};
var merchant2 = new MerchantModel
{
AppId = 2,
Name = "Ted"
};
var merchant3 = new MerchantModel
{
AppId = 3,
Name = "Alice"
};
List<MerchantModel> list = new List<MerchantModel>();
list.Add(merchant1);
list.Add(merchant2);
list.Add(merchant3);
var model = new MerchantViewModel
{
Merchants = list
};
return View(model);
}
[HttpPost]
public ActionResult Index(MerchantViewModel model)
{
return View(model);
}
}
View:
#model TestCheckBoxes.Models.MerchantViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<form action="/default/index" method="post">
<table>
#for (int i = 0; i < Model.Merchants.Count; i++)
{
<tr>
<td>
#Html.CheckBoxFor(x => x.Merchants[i].IsSelected)
</td>
<td>
#Html.HiddenFor(x => x.Merchants[i].AppId)
#Model.Merchants[i].AppId
</td>
<td>
#Html.HiddenFor(x => x.Merchants[i].Name)
#Model.Merchants[i].Name
</td>
</tr>
}
</table>
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>
Back in your [HttpPost] method in your controller, you will have a list of MerchantModel's with the bool value either true or false. This way you can check if it's true and just grab the AppId from there.
Don't use foreach in mvc, always iterate using for and an indexing variable.
You'll also need a bool to track the selection status.
This example code works for me:
public class AModel
{
public List<AnotherModel> Items { get; set; }
}
public class AnotherModel
{
public int ApplicationId { get;set; }
public DateTime ApplicationDate { get; set; }
public string ApplicantName { get; set; }
public bool Selected { get; set; }
}
Page.cshtml
#using (Html.BeginForm("PostIndex", "Home", FormMethod.Post))
{
<table class="table" style="margin-bottom: 0px">
<tbody>
#for (var i = 0; i < Model.Items.Count(); i++)
{
<tr>
<td>
<label>#Html.CheckBoxFor(model => model.Items[i].Selected) #Html.DisplayFor(model => model.Items[i].ApplicantName)</label>
</td>
<td>
#Html.ActionLink(Model.Items[i].ApplicationId.ToString(), "ViewApplication", new {ID = Model.Items[i].ApplicationId, edit = 1}, new AjaxOptions {HttpMethod = "GET"})
</td>
<td>
#Html.DisplayFor(model => model.Items[i].ApplicationDate)
</td>
<td>
#Html.DisplayFor(model => model.Items[i].ApplicationId)
</td>
</tr>
}
</tbody>
</table>
<input type="submit"/>
}
#CBauer and #NickYoung essentially had the answer. The keys were (1) making sure my checkboxes had the ID written with a sequential number in brackets with the same suffix, (2) using a submit button instead of an action link, and (3) correctly writing the controller to accept the IDs from the checkboxes. Thought I'd post some of my code to give you an idea of what I got to work:
View (partial):
#model PagedList.IPagedList<CarmelFinancialWeb.Models.ModelMerchantSummary>
...
#{var i = 0;}
#foreach (var item in Model)
{
var tmp = "[" + i + "].ints";
<tr>
<td>
<input name="ints" type="checkbox" id="#tmp" class="chkclass" value="#item.ApplicationID" />
</td>
...
<input id="Submit" type="submit" class="btn btn-primary" value="Print Application(s)" />
...
Controller:
[AuthorizeAdmin]
[HttpPost]
public ActionResult MerchantApplicationSummary(string[] ints, FormCollection form, int? page)
{
...
Thanks #CBauer and #NickYoung for your help!
I'm working on a small project. The intention is to maintain the presences of a couple of users on some specific dates. This dates are first chosen by the user.
Therefor I use a view model. This will provide all possible data with a check box in a table to show to the user.
In the view itself I walk every day in the given view modeland I let the view generate a tag and an editor object (Html.EditorFor ()). All this is surrounded by the form creation (# Html.BeginForm ()). Rendering the view is not the problem.
The problem is when I try to return the view model. The viewmodel object that I receive is an object with null - objects in themselves. Like it has been created by the default constructor.
Controller:
[HttpGet]
public ActionResult OpldagenLt()
{
var lt = _gebruikerRepository.GeefTraject(_gebruikerRepository.TrajectId);
List<DatumModel> data = new List<DatumModel>();
foreach (Opleidingdag opldag in lt.GeefOpleidingdagenKleinerDanOfGelijkAanVandaag())
data.Add(new DatumModel(opldag));
List<ToekomstModel> toekomst = new List<ToekomstModel>();
foreach (Opleidingdag opldag in lt.GeefOpleidingdagenGroterDanVandaag())
toekomst.Add(new ToekomstModel(opldag));
DataModel datamod = new DataModel();
datamod.Datums = data;
datamod.Toekomst = toekomst;
if (lt.ControleerAantalOpleidingdagen())
{
_gebruikerRepository.GekozenDagen = GekozenDagen(datamod) as List<Opleidingdag>;
return RedirectToAction("Index", "Aanwezigheid");
}
return View(datamod);
}
[HttpPost]
public ActionResult OpldagenLt(DataModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
_gebruikerRepository.GekozenDagen = GekozenDagen(model) as List<Opleidingdag>;
return RedirectToAction("Index", "Aanwezigheid");
}
public ICollection<Opleidingdag> GekozenDagen(DataModel datamod)
{
List<Opleidingdag> dagen = new List<Opleidingdag>();
foreach (DatumModel datum in datamod.Datums)
{
dagen.Add(datum.Dag);
}
return dagen;
}
View:
#using(#Html.BeginForm( "OpldagenLt", "Leertraject", FormMethod.Post))
{
<div>
<table>
<tr>
<th colspan="2">reeds begonnen dagen</th>
</tr>
#foreach (var item in #Model.Datums)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.Dag.Dag.Day)/#Html.DisplayFor(modelItem => item.Dag.Dag.Month)/#Html.DisplayFor(modelItem => item.Dag.Dag.Year)</td>
<td>#Html.EditorFor(modelItem => item.Checked)</td>
</tr>
}
</table>
</div>
<div id="toekomst">
<table>
<tr>
<th>Dagen in de toekomst</th>
</tr>
#foreach (var item in #Model.Toekomst)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.Dag.Dag.Day)/#Html.DisplayFor(modelItem => item.Dag.Dag.Month)/#Html.DisplayFor(modelItem => item.Dag.Dag.Year)</td>
</tr>
}
</table>
</div>
<div>
<p><input type="submit" value="Volgende"/></p>
</div>
}
Model:
using System;
using System.Collections.Generic;
using ProjectII.Models.domain;
namespace ProjectII.Viewmodels
{
public class DataModel
{
public DataModel()
{
Datums = new List<DatumModel>();
}
public ICollection<DatumModel> Datums { get; set; }
public ICollection<ToekomstModel> Toekomst{ get; set; }
}
public class DatumModel
{
public DatumModel()
{
Dag = new Opleidingdag(new DateTime().Date);
Checked = true;
}
public DatumModel(Opleidingdag opldag)
{
Dag = opldag;
Checked = true;
}
public Opleidingdag Dag { get; set; }
public bool Checked { get; set; }
}
public class ToekomstModel
{
public ToekomstModel()
{
Dag = new Opleidingdag(new DateTime().Date);
}
public ToekomstModel(Opleidingdag opldag)
{
Dag = opldag;
}
public Opleidingdag Dag { get; set; }
}
}
Thanks in advance for the help
With the way you construct your view, the ModelBinder cannot differantiate between the different elements in the list, and doesn't recognize them as items in the list. Try constructing the view like this:
#{ int datumteller = 0; }
#foreach (var item in #Model.Datums)
{
<tr>
<td>#Html.DisplayFor(modelItem => #Model.Datums[datumteller].Dag.Dag.Day)/#Html.DisplayFor(modelItem => #Model.Datums[datumteller].Dag.Dag.Month)/#Html.DisplayFor(modelItem => #Model.Datums[datumteller].Dag.Dag.Year)</td>
<td>#Html.EditorFor(modelItem => #Model.Datums[datumteller].Checked)</td>
</tr>
datumteller++;
}
#{ int toekomstteller = 0; }
#foreach (var item in #Model.Toekomst)
{
<tr>
<td>#Html.DisplayFor(modelItem => #Model.Toekomst[toekomstteller].Dag.Dag.Day)/#Html.DisplayFor(modelItem => #Model.Toekomst[toekomstteller].Dag.Dag.Month)/#Html.DisplayFor(modelItem => #Model.Toekomst[toekomstteller].Dag.Dag.Year)</td>
</tr>
toekomstteller++
}
#stephen: thanks for the help.
with keeping your answer in my mind I finally succeeded returning those data.
I changed the foreach into a for
and changed ICollection to a List
Model:
using System;
using System.Collections.Generic;
using ProjectII.Models.domain;
namespace ProjectII.Viewmodels
{
public class DataModel
{
public List<DatumModel> Datums { get; set; }
public List<ToekomstModel> Toekomst{ get; set; }
}
public class DatumModel
{
public DatumModel()
{
Dag = new Opleidingdag(new DateTime().Date);
Checked = true;
}
public DatumModel(Opleidingdag opldag)
{
Dag = opldag;
Checked = true;
}
public Opleidingdag Dag { get; set; }
public bool Checked { get; set; }
}
public class ToekomstModel
{
public ToekomstModel()
{
Dag = new Opleidingdag(new DateTime().Date);
}
public ToekomstModel(Opleidingdag opldag)
{
Dag = opldag;
}
public Opleidingdag Dag { get; set; }
}
}
view:
#model ProjectII.Viewmodels.DataModel
#using(#Html.BeginForm())
{
<div>
<table>
<tr>
<th colspan="2">reeds begonnen dagen</th>
</tr>
#for (int i = 0; i < Model.Datums.Count; i++)
{
<tr>
<td>#Html.DisplayFor(modelItem => Model.Datums[i].Dag.Dag.Day)/#Html.DisplayFor(modelItem => Model.Datums[i].Dag.Dag.Month)/#Html.DisplayFor(modelItem => Model.Datums[i].Dag.Dag.Year)</td>
<td>
#Html.EditorFor(modelItem => Model.Datums[i].Checked)
</td>
</tr>
}
</table>
#*#for (int i = 0; i < Model.Datums.Count; i++)
{
<div> #Html.DisplayFor(x => Model.Datums[i].Dag.Dag)
#Html.CheckBoxFor(x => Model.Datums[i].Checked) </div>
}*#
</div>
<div id="toekomst">
<table>
<tr>
<th>Dagen in de toekomst</th>
</tr>
#foreach (var item in #Model.Toekomst)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.Dag.Dag.Day)/#Html.DisplayFor(modelItem => item.Dag.Dag.Month)/#Html.DisplayFor(modelItem => item.Dag.Dag.Year)</td>
</tr>
}
</table>
</div>
<div>
<p><input type="submit" value="Volgende"/></p>
</div>
}
Now I recieve a model with the right values
thanks for the help people