When updating Marking entity datetime property unchanged - asp.net-mvc-3

I have this entity service in my domain model with two datetime type properties entrydate and updatedon.
When user in edit view make any changes and submit form back I want entrydate property of the postedback/modified object to be marked as unchanged so entrydate can't be overwritten when performing updates.
public class Service
{
public int ServiceID
{
get;
set;
}
[Required(ErrorMessage="Please enter Name")]
public string Name
{
get;
set;
}
[Required(ErrorMessage="Please enter the duration for the service")]
public short Duration
{
get;
set;
}
[DataType(DataType.Date)]
public DateTime EntryDate
{
get;
set;
}
[DataType(DataType.Date)]
public DateTime UpdatedOn
{
get;
set;
}
public decimal Cost
{
get; set;
}
}
Repository method that is persisting changes into db is as follows:
public void InsertOrUpdate(Service service)
{
if (service.ServiceID == default(int)) {
// New entity
context.Services.Add(service);
} else {
// Existing entity
context.Entry(service).State = EntityState.Modified;
}
}

You can reload the original entity from the database:
else {
// Existing entity
var serviceInDb = context.Services.Find(service.ServiceID);
service.EntryDate = serviceInDb.EntryDate;
context.Entry(serviceInDb).CurrentValues.SetValues(service);
}
When you call SaveChanges later an UPDATE statement only for properties which have really changed will be sent to the database (has also benefits for other unchanged properties).
Or just reload the EntryDate:
else {
// Existing entity
var entryDateInDb = context.Services
.Select(s => s.EntryDate)
.Single(s => s.ServiceID == service.ServiceID);
service.EntryDate = entryDateInDb;
context.Entry(service).State = EntityState.Modified;
}
Another working but ugly approach is this:
context.Services.Attach(service); // thanks to user202448, see comments
context.Entry(service).Property(s => s.Name).IsModified = true;
context.Entry(service).Property(s => s.Duration).IsModified = true;
context.Entry(service).Property(s => s.UpdatedOn).IsModified = true;
context.Entry(service).Property(s => s.Cost).IsModified = true;
So, don't set the EntryDate property to modified but all the other properties one by one.
The approach which comes into mind ...
context.Entry(service).State = EntityState.Modified;
context.Entry(service).Property(s => s.EntryDate).IsModified = false;
... unfortunately doesn't work because setting back a property to not-modified which is already marked as Modified is not supported and will throw an exception.

Related

Dynamic LINQ: Comparing Nested Data With Parent Property

I've a class with following structure:
public class BestWayContext
{
public Preference Preference { get; set; }
public DateTime DueDate { get; set; }
public List<ServiceRate> ServiceRate { get; set; }
}
public class ServiceRate
{
public int Id { get; set; }
public string Carrier { get; set; }
public string Service { get; set; }
public decimal Rate { get; set; }
public DateTime DeliveryDate { get; set; }
}
and I've dynamic linq expression string
"Preference != null && ServiceRate.Any(Carrier == Preference.Carrier)"
and I want to convert above string in Dynamic LINQ as follows:
var expression = System.Linq.Dynamic.DynamicExpression.ParseLambda<BestWayContext, bool>(condition, null).Compile();
But it showing following error:
Please correct me what am I doing wrong?
It looks like you wanted to do something like this:
var bwc = new BestWayContext
{
Preference = new Preference { Carrier = "test" },
DueDate = DateTime.Now,
ServiceRate = new List<ServiceRate>
{
new ServiceRate
{
Carrier = "test",
DeliveryDate = DateTime.Now,
Id = 2,
Rate = 100,
Service = "testService"
}
}
};
string condition = "Preference != null && ServiceRate.Any(Carrier == #0)";
var expression = System.Linq.Dynamic.DynamicExpression.ParseLambda<BestWayContext, bool>(condition, bwc.Preference.Carrier).Compile();
bool res = expression(bwc); // true
bwc.ServiceRate.First().Carrier = "test1"; // just for testing this -> there is only one so I've used first
res = expression(bwc); // false
You want to use Preference which belong to BestWayContext but you didn't tell the compiler about that. If i write your expression on Linq i will do as follows:
[List of BestWayContext].Where(f => f.Preference != null && f.ServiceRate.Where(g => g.Carrier == f.Preference.Carrier)
);
As you see i specified to use Preference of BestWayContext.

kendo scheduler not return date on server side using mvc

I am having issue of using Kendo UI scheduler,
When I schedule task ,
Kendo UI start and end date not returning on server side.
Start and end date always return default date.
Here a Razor Code :
#model IEnumerable<Web.Models.PlantColor>
#{
ViewBag.Title = "Schedule View";
}
<h2>Schedule View</h2>
#(Html.Kendo().Scheduler<WorkScheduler.Web.Models.KendoSchedular>()
.Name("scheduler")
.Date(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day))
.StartTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 08, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WorkWeekView();
views.WeekView();
views.MonthView();
views.AgendaView();
})
.Resources(resource =>
{
resource.Add(m => m.PlantId)
.Title("Owner")
.DataTextField("Text")
.DataValueField("Value")
.DataColorField("Color")
.BindTo(Model);
})
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.id);
})
.Read("ReadSchedule", "ScheduleView")
.Create("CreateSchedule", "ScheduleView")
.Destroy("Destroy", "ScheduleView")
.Update("Update", "ScheduleView")
)
)
Make sure that you have the start and end fields defined in your Model that you are posting back (and model inherits from ISchedulerEvent):
public class CalendarAppointmentViewModel : ISchedulerEvent
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Recurrence { get; set; }
public string StartTimezone { get; set; }
public string EndTimezone { get; set; }
private DateTime start;
public DateTime Start
{
get
{
return start;
}
set
{
start = value.ToUniversalTime();
}
}
private DateTime end;
public DateTime End
{
get
{
return end;
}
set
{
end = value.ToUniversalTime();
}
}
public string RecurrenceRule { get; set; }
public int? RecurrenceID { get; set; }
public string RecurrenceException { get; set; }
public bool IsAllDay { get; set; }
I can see this question is already accepted as best answer. Perhaps following might be helpful also for someone struggling to return Start/End dates from Editor of Kendo Scheduler.
I had same issue, and followed the solutions provided here, still no success. In my case defining the culture and creating a Model inherited from "ISchedulerEvent" was still returning default date to the server side in Create & Update events handler methods of the Controller.
For me problem was a missing .js file.
kendo.timezones.min.js
So for anyone who is in the same shoes like me, kindly look at your Scripts folder in the project, and if that .js file is missing.
And please follow these steps in setting up the project.

KendoUI Scheduler

I am trying to implement the scheduler control to show live calculation of material usage on daily bases (in a week by week view).
I am unable to have the Usage data displayed in the cells although I managed to have to Materials displayed on the left hand side. I wonder if any one could help or give me some hints on what I am doing wrong. Here is my code so far:
I can be sure that data is being return to the view but the view is not showing the usage data, which is simply numeric values corresponding to a material on a specific day of the week. I have also attached a screenshot of how it looks like:
the Controller method to read the data:
public JsonResult Read([DataSourceRequest] DataSourceRequest request)
{
try
{
var usageList = new List<ReportUsageViewModel>();
var imports = _importRespository.GetImports();
foreach (var usageReportStoredProcedure in imports)
{
var usageViewModel = new ReportUsageViewModel();
usageViewModel.MaterialID = usageReportStoredProcedure.MaterialID;
usageViewModel.Start = usageReportStoredProcedure.ScanDate;
usageViewModel.End = usageReportStoredProcedure.ScanDate;
usageViewModel.DailyUsage = usageReportStoredProcedure.UsageQuantity;
usageViewModel.Title = usageReportStoredProcedure.UsageQuantity.ToString();
usageList.Add(usageViewModel);
}
return Json(usageList.ToDataSourceResult(request));
}
catch (Exception exc)
{
ErrorHelper.WriteToEventLog(exc);
return null;
}
}
The actual control
<div id="StockViewer">
#(Html.Kendo().Scheduler<WorcesterMarble.ViewModels.ReportUsageViewModel>()
.Name("StockViewer")
.Timezone("Europe/London")
.Resources(resource => resource.Add(m => m.MaterialID)
.Title("Materials")
.Name("Materials")
.DataTextField("Name")
.DataValueField("MaterialID")
.BindTo(Model.MaertiaList))
.MajorTick(270)
.MinorTickCount(1)
.StartTime(DateTime.Now.Date.AddHours(8))
.EndTime(DateTime.Now.Date.AddHours(17))
.AllDaySlot(false)
.Date(DateTime.Now.Date)
.Editable(false)
.Views(x => x.WeekView(v =>
{
v.Footer(false);
v.Selected(true);
v.DateHeaderTemplate("<span class='k-link k-nav-day'>#=kendo.toString(date, 'ddd dd/M')#</span>");
}))
.Group(group => group.Resources("Materials").Orientation(SchedulerGroupOrientation.Vertical))
.DataSource(d => d
.Model(m => {
m.Id(f => f.MaterialID);
m.Field(f => f.Title).DefaultValue("No title");
})
.Read("Read", "ReportUsage")
)
)
Update: This is the ViewModel implementing the ISchedulerEvent
public class ReportUsageViewModel : ISchedulerEvent
{
public int MaterialID { get; set; }
public string MaterialName { get; set; }
public int? DailyUsage { get; set; }
public List<MaterialViewModel> MaertiaList { get; set; }
public string Description { get; set; }
public System.DateTime End { get; set; }
public bool IsAllDay { get; set; }
public string RecurrenceException { get; set; }
public string RecurrenceRule { get; set; }
public System.DateTime Start { get; set; }
public string Title { get; set; }
}
The issue was in these two lines:
.StartTime(DateTime.Now.Date.AddHours(8))
.EndTime(DateTime.Now.Date.AddHours(17))
The data was there but these two lines were hiding it. The data was being logged at times outside the time range of 8 to 17 so I removed these two lines and then set the Major ticks to 1440, which is the total number of ticks in 24 hrs, which helped me hiding the time column as I didn't need it..

Edit on Model - complex types not updated properly

I have this two objects - Magazine and Author (M-M relationship):
public partial class MAGAZINE
{
public MAGAZINE()
{
this.AUTHORs = new HashSet<AUTHOR>();
}
public long REF_ID { get; set; }
public string NOTES { get; set; }
public string TITLE { get; set; }
public virtual REFERENCE REFERENCE { get; set; }
public virtual ICollection<AUTHOR> AUTHORs { get; set; }
}
public partial class AUTHOR
{
public AUTHOR()
{
this.MAGAZINEs = new HashSet<MAGAZINE>();
}
public long AUTHOR_ID { get; set; }
public string FULL_NAME { get; set; }
public virtual ICollection<MAGAZINE> MAGAZINEs { get; set; }
}
}
My problem is that I can't seem to update the number of authors against a magazine e.g. if I have 1 author called "Smith, P." stored already against a magazine, I can add another called "Jones, D.", but after the post back to the Edit controller the number of authors still shows 1 - i.e. "Smith, P.H".
Please not that I have successfully model bound the number of authors back to the parent entity (Magazine), it uses a custom model binder to retrieve the authors and bind to the Magazine (I think), but it still doesn't seem to update properly.
My code for updating the model is straight forward - and shows the variable values both before and after:
public ActionResult Edit(long id)
{
MAGAZINE magazine = db.MAGAZINEs.Find(id);
return View(magazine);
}
and here are the variables pre-editing/updating -
[HttpPost]
public ActionResult Edit(MAGAZINE magazine)
{
if (ModelState.IsValid)
{
db.Entry(magazine).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(magazine);
}
...and here are the variables after a new author has been added...
I am getting suspicious that the author entity is showing, post edit that it is not bound to any magazine and I am guessing this is why it is not being updated back to the magazine entity - but it is perplexing as I am effectively dealing with the same magazine entity - I guess it may be something to do with the custom model binder for the author.
Can anyone help on this matter?
For completeness - I have included my AuthorModelBinder class too -
public class AuthorModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (values != null)
{
// We have specified asterisk (*) as a token delimiter. So
// the ids will be separated by *. For example "2*3*5"
var ids = values.AttemptedValue.Split('*');
List<int> validIds = new List<int>();
foreach (string id in ids)
{
int successInt;
if (int.TryParse(id, out successInt))
{
validIds.Add(successInt);
}
else
{
//Make a new author
AUTHOR author = new AUTHOR();
author.FULL_NAME = id.Replace("\'", "").Trim();
using (RefmanEntities db = new RefmanEntities())
{
db.AUTHORs.Add(author);
db.SaveChanges();
validIds.Add((int)author.AUTHOR_ID);
}
}
}
//Now that we have the selected ids we could fetch the corresponding
//authors from our datasource
var authors = AuthorController.GetAllAuthors().Where(x => validIds.Contains((int)x.Key)).Select(x => new AUTHOR
{
AUTHOR_ID = x.Key,
FULL_NAME = x.Value
}).ToList();
return authors;
}
return Enumerable.Empty<AUTHOR>();
}
}
I faced a very similar scenario when I developed my blog using MVC/Nhibernate and the entities are Post and Tag.
I too had an edit action something like this,
public ActionResult Edit(Post post)
{
if (ModelState.IsValid)
{
repo.EditPost(post);
...
}
...
}
But unlike you I've created a custom model binder for the Post not Tag. In the custom PostModelBinder I'm doing pretty much samething what you are doing there (but I'm not creating new Tags as you are doing for Authors). Basically I created a new Post instance populating all it's properties from the POSTed form and getting all the Tags for the ids from the database. Note that, I only fetched the Tags from the database not the Post.
I may suggest you to create a ModelBinder for the Magazine and check it out. Also it's better to use repository pattern instead of directly making the calls from controllers.
UPDATE:
Here is the complete source code of the Post model binder
namespace PrideParrot.Web.Controllers.ModelBinders
{
[ValidateInput(false)]
public class PostBinder : IModelBinder
{
private IRepository repo;
public PostBinder(IRepository repo)
{
this.repo = repo;
}
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;
// retrieving the posted values.
string oper = request.Form.Get("oper"),
idStr = request.Form.Get("Id"),
heading = request.Form.Get("Heading"),
description = request.Form.Get("Description"),
tagsStr = request.Form.Get("Tags"),
postTypeIdStr = request.Form.Get("PostType"),
postedDateStr = request.Form.Get("PostedDate"),
isPublishedStr = request.Form.Get("Published"),
fileName = request.Form.Get("FileName"),
serialNoStr = request.Form.Get("SerialNo"),
metaTags = request.Form.Get("MetaTags"),
metaDescription = request.Form.Get("MetaDescription"),
themeIdStr = request.Form.Get("Theme");
// initializing to default values.
int id = 0, serialNo = 0;
DateTime postedDate = DateTime.UtcNow;
DateTime? modifiedDate = DateTime.UtcNow;
postedDate.AddMilliseconds(-postedDate.Millisecond);
modifiedDate.Value.AddMilliseconds(-modifiedDate.Value.Millisecond);
/*if operation is not specified throw exception.
operation should be either'add' or 'edit'*/
if (string.IsNullOrEmpty(oper))
throw new Exception("Operation not specified");
// if there is no 'id' in edit operation add error to model.
if (string.IsNullOrEmpty(idStr) || idStr.Equals("_empty"))
{
if (oper.Equals("edit"))
bindingContext.ModelState.AddModelError("Id", "Id is empty");
}
else
id = int.Parse(idStr);
// check if heading is not empty.
if (string.IsNullOrEmpty(heading))
bindingContext.ModelState.AddModelError("Heading", "Heading: Field is required");
else if (heading.Length > 500)
bindingContext.ModelState.AddModelError("HeadingLength", "Heading: Length should not be greater than 500 characters");
// check if description is not empty.
if (string.IsNullOrEmpty(description))
bindingContext.ModelState.AddModelError("Description", "Description: Field is required");
// check if tags is not empty.
if (string.IsNullOrEmpty(metaTags))
bindingContext.ModelState.AddModelError("Tags", "Tags: Field is required");
else if (metaTags.Length > 500)
bindingContext.ModelState.AddModelError("TagsLength", "Tags: Length should not be greater than 500 characters");
// check if metadescription is not empty.
if (string.IsNullOrEmpty(metaTags))
bindingContext.ModelState.AddModelError("MetaDescription", "Meta Description: Field is required");
else if (metaTags.Length > 500)
bindingContext.ModelState.AddModelError("MetaDescription", "Meta Description: Length should not be greater than 500 characters");
// check if file name is not empty.
if (string.IsNullOrEmpty(fileName))
bindingContext.ModelState.AddModelError("FileName", "File Name: Field is required");
else if (fileName.Length > 50)
bindingContext.ModelState.AddModelError("FileNameLength", "FileName: Length should not be greater than 50 characters");
bool isPublished = !string.IsNullOrEmpty(isPublishedStr) ? Convert.ToBoolean(isPublishedStr.ToString()) : false;
//** TAGS
var tags = new List<PostTag>();
var tagIds = tagsStr.Split(',');
foreach (var tagId in tagIds)
{
tags.Add(repo.PostTag(int.Parse(tagId)));
}
if(tags.Count == 0)
bindingContext.ModelState.AddModelError("Tags", "Tags: The Post should have atleast one tag");
// retrieving the post type from repository.
int postTypeId = !string.IsNullOrEmpty(postTypeIdStr) ? int.Parse(postTypeIdStr) : 0;
var postType = repo.PostType(postTypeId);
if (postType == null)
bindingContext.ModelState.AddModelError("PostType", "Post Type is null");
Theme theme = null;
if (!string.IsNullOrEmpty(themeIdStr))
theme = repo.Theme(int.Parse(themeIdStr));
// serial no
if (oper.Equals("edit"))
{
if (string.IsNullOrEmpty(serialNoStr))
bindingContext.ModelState.AddModelError("SerialNo", "Serial No is empty");
else
serialNo = int.Parse(serialNoStr);
}
else
{
serialNo = repo.TotalPosts(false) + 1;
}
// check if commented date is not empty in edit.
if (string.IsNullOrEmpty(postedDateStr))
{
if (oper.Equals("edit"))
bindingContext.ModelState.AddModelError("PostedDate", "Posted Date is empty");
}
else
postedDate = Convert.ToDateTime(postedDateStr.ToString());
// CREATE NEW POST INSTANCE
return new Post
{
Id = id,
Heading = heading,
Description = description,
MetaTags = metaTags,
MetaDescription = metaDescription,
Tags = tags,
PostType = postType,
PostedDate = postedDate,
ModifiedDate = oper.Equals("edit") ? modifiedDate : null,
Published = isPublished,
FileName = fileName,
SerialNo = serialNo,
Theme = theme
};
}
#endregion
}
}
This line db.Entry(magazine).State = EntityState.Modified; only tells EF that magazine entity has changed. It says nothing about relations. If you call Attach all entities in object graph are attached in Unchanged state and you must handle each of them separately. What is even worse in case of many-to-many relation you must also handle relation itself (and changing state of relation in DbContext API is not possible).
I spent a lot of time with this problem and design in disconnected app. And there are three general approaches:
You will send additional information with your entities to find what has changed and what has been deleted (yes you need to track deleted items or relations as well). Then you will manually set state of every entity and relation in object graph.
You will just use data you have at the moment but instead of attaching them to the context you will load current magazine and every author you need and reconstruct those changes on those loaded entities.
You will not do this at all and instead use lightweight AJAX calls to add or remove every single author. I found this common for many complex UIs.

MVC 3 Post of Viewmodel with Completex IEnumerable

I have a complex class that is part of a property of a viewmodel. My viewmodel has a wine class property and a wine class has a ICollection property called CaseProductions. The CaseProduction class has several properties as well.
On the create GET event, the NewWineViewModel is instantiated, then it runs a GetCaseProductionDefaults with create a list of CaseProduction classes that have some default values, but are mostly empty.
Now, I originally used razor to do a foreach statement and just pop out my table the way I wanted it. But I've see around that doesn't work to bind this type of IEnumerable back to the viewmodel on POST. I've tried to use the below, but no dice.
EditorFor(m => m.Wine.CaseProductions)
I'm really looking for advise on what the best way to handle this is. Each wine will have a collection of caseproductions, and I want that to bind back to the wine within the viewmodel. Is their some way I can edit the ids of those elements in razor to make sure they bind? What's the best way to handle this one?
viewmodel:
public class NewWineViewModel
{
public Wine Wine { get; set; }
public VOAVIRequest VOAVIRequest { get; set; }
public bool IsRequest { get; set; }
public Dictionary<int, int> BottlesPerCase { get; set; }
public SelectList VarTypes { get; set; }
public SelectList Origins { get; set; }
public SelectList Apps { get; set; }
public SelectList Vintages { get; set; }
public SelectList Importers { get; set; }
}
case production class:
public class CaseProduction
{
public int CaseProductionID { get; set; }
public int WineID { get; set; }
public int CaseProductionSizeID { get; set; }
public int CaseCount { get; set; }
public int CountPerCase { get; set; }
public virtual CaseProductionSize CaseProductionSize { get; set; }
public virtual Wine Wine { get; set; }
}
getting default case productions:
public List<CaseProduction> GetCaseProductionDefaults(vfContext db)
{
//creates blank list of all formats
List<CaseProduction> cp = new List<CaseProduction>();
foreach (CaseProductionSize size in db.CaseProductionSizes)
{
int defaultBottlesPerCase = 1;
switch ((CaseProductionSizeEnum)size.CaseProductionSizeID)
{
case CaseProductionSizeEnum.s187ml:
defaultBottlesPerCase= 24;
break;
case CaseProductionSizeEnum.s375ml:
defaultBottlesPerCase = 12;
break;
case CaseProductionSizeEnum.s500ml:
defaultBottlesPerCase = 12;
break;
case CaseProductionSizeEnum.s750ml:
defaultBottlesPerCase = 12;
break;
default:
defaultBottlesPerCase = 1;
break;
}
cp.Add(new CaseProduction { CaseProductionSizeID = size.CaseProductionSizeID, CountPerCase = defaultBottlesPerCase, CaseProductionSize = size, WineID = this.Wine.WineID });
}
return cp;
}
my razor code for the case production table:
#foreach (vf2.Models.CaseProduction cp in Model.Wine.CaseProductions)
{
<tr>
<td>#cp.CaseProductionSize.Name
</td>
<td>#Html.Raw(#Html.TextBoxFor(m => m.Wine.CaseProductions.Where(c => c.CaseProductionSizeID == cp.CaseProductionSizeID).First().CaseCount, new { #class = "caseCount", id = "txt" + cp.CaseProductionSize.Name }).ToString().Replace("CaseCount","txt" + cp.CaseProductionSize.Name))
</td>
<td>
#Html.DropDownListFor(m => m.Wine.CaseProductions.Where(c => c.CaseProductionSizeID == cp.CaseProductionSizeID).First().CountPerCase, new SelectList(Model.BottlesPerCase, "Key", "Value", cp.CountPerCase), new { #class = "countPerCase", id = "ddl" + cp.CaseProductionSize.Name, name = "ddl" + cp.CaseProductionSize.Name})
</td>
<td class="totalBottleCalc">
</td>
</tr>
}
instantiation of my caseproduction collection:
public ActionResult Create(int ID = 0, int VintUpID = 0)
{
NewWineViewModel nw = new NewWineViewModel();
nw.Wine.CaseProductions = nw.GetCaseProductionDefaults(db);
nw.BottlesPerCase = nw.GetBottlesPerCase(db);
I believe the model binder isn't picking up on your CaseProduction objects because they don't look like a CaseProduction objects.
You have renamed CaseCount, your CaseProductionSize has no Id (nor does you CaseProduction, and it's missing several properties. In your loop you have to include all properties, and keep the names consistent with the names of your POCOs. Otherwise the model binder won't know what they are. You can put all the properties in hidden fields if you want.
You must instantiate your nested Lists and complex models in your parent models constructor. The default model binder will not instantiate child classes.
If you do that, then you can use the EditorFor(m => m.Wine.CaseProductions) should work, and you don't need the complex view code you are using.
If you want to customize how the CaseProduction is rendered, then you can create a CaseProduction.cshtml file in ~/Shared/EditorTemplates and it will use this definition to render each item in the collection (it will automatically iterate over the collection for you).
Also, you shouldn't do linq queries in your view. Your problem there is that it looks like you're passing your data entity directly to the view. This is bad design. You need to instead create a ViewModel that contains only the information needed to render the view. Then, you filter your data before you assign it to the View model.

Resources