asp.net MVC Checkboxes DaysOfWeek enum - asp.net

I am working on a form that can be used to add new records and update existing records.
One form element is to capture multiple choices of week days. I therefore implemented an DayOfWeek Enum.
This is how my model looks like
public class EventFormModel
{
public EventFormModel()
{
AvailableDays = (from DayOfWeek d in Enum.GetValues(typeof(DayOfWeek))
select new MyDay
{
Id = (int)d,
Name = d.ToString()
}
public List<MyDay> AvailableDays { get; set; }
public int[] SelectedDays { get; set; }
}
}
public class MyDay
{
public string Name { get; set; }
public int Id { get; set; }
}
My View looks like this
#foreach (var day in Model.AvailableDays)
{
<input type="checkbox" name="SelectedDays" value="#day.Id"
#if (Model.SelectedDays != null && Model.SelectedDays.Contains(day.Id))
{
<text>checked="checked"</text>
}
/>#day.Name.Substring(0,3)
}
Now I am facing 2 problems, For 1 I can't figure out how to retrieve the values from my checkboxes ones they are posted to the controller and 2 how would I populate the checkboxlist with values I stored in my database ie SelectedDays = 1,4,6.
I hope I am approaching this the correct way in the first place. any help would be appreciated.

It never ceases to amaze me how people insist on writing their own html, and then are confused why things don't work.
Stick with the html helpers whenever possible. Change your model a bit... Make SelectedDays an array of bool[7]
#for(int i = 0; i < Model.SelectedDays.Count; i++)
{
#Html.CheckBoxFor(x => x.SelectedDays[i])
}
Now the checkboxes automatically populate, and default to unchecked.
Alternatively, you could add a "selected" bool field to your MyDay class, then change it to:
#for(int i = 0; i < Model.AvailableDays.Count; i++)
{
#Html.CheckBoxFor(x => x.AvailableDays[i].Selected)
}
Note: Do not change this to use a foreach, if you do, it won't create the proper indexing for the name fields to post the collection values.

After tinkering with this for a while I came up with this working solution.
Here is the model
public class EventFormModel
{
public EventFormModel()
{
AvailableDays = (from DayOfWeek d in Enum.GetValues(typeof(DayOfWeek))
select new MyDay
{
Id = (int)d,
Name = d.ToString()
}
public List<MyDay> AvailableDays { get; set; }
}
}
public class MyDay
{
public string Name { get; set; }
public int Id { get; set; }
public bool Selected { get; set; }
}
Here is the View
#for(int i = 0; i < Model.AvailableDays.Count; i++)
{
<div>
#Html.CheckBoxFor(x => x.AvailableDays[i].Selected)
#Html.HiddenFor(x => x.AvailableDays[i].Name)
#Model.AvailableDays[i].Name
</div>
}
Here is the Controller
[AcceptVerbs(HttpVerbs.Post), Authorize]
public ActionResult AddEvent(EventFormModel model)
{
string days = "";
for(int i = 0; i < model.AvailableDays.Count; i++)
{
if (model.AvailableDays[i].Selected)
{
days = days + model.AvailableDays[i].Name + ",";
}
}
//Do something with your selected days
return View(model);
}
To populate the checkboxes with select items
string[] stringArray = "Sun,Mon,Tue,Wed".Split(',').ToArray<string>();
model.AvailableDays = (from DayOfWeek d in Enum.GetValues(typeof(DayOfWeek))
select new TestDay
{
Id = (int)d,
Name = d.ToString().Substring(0, 3),
Selected = stringArray.Contains(d.ToString().Substring(0, 3))
}).ToList();

Related

ASP.Net MVC : Binding Dropdownlist to a List on the Model [duplicate]

I'm developing an ASP.NET MVC 5 application, with C# and .NET Framework 4.6.1.
I have this View:
#model MyProject.Web.API.Models.AggregationLevelConfViewModel
[...]
#Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, (SelectList)Model.HelperCodeTypeItems, new { id = "Configurations[0].HelperCodeType" })
The ViewModel is:
public class AggregationLevelConfViewModel
{
private readonly List<GenericIdNameType> codeTypes;
private readonly List<GenericIdNameType> helperCodeTypes;
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
public int ProductionOrderId { get; set; }
public string ProductionOrderName { get; set; }
public IList<Models.AggregationLevelConfiguration> Configurations { get; set; }
public AggregationLevelConfViewModel()
{
// Load CodeTypes to show it as a DropDownList
byte[] values = (byte[])Enum.GetValues(typeof(CodeTypes));
codeTypes = new List<GenericIdNameType>();
helperCodeTypes = new List<GenericIdNameType>();
for (int i = 0; i < values.Length; i++)
{
GenericIdNameType cType = new GenericIdNameType()
{
Id = values[i].ToString(),
Name = EnumHelper.GetDescription((CodeTypes)values[i])
};
if (((CodeTypes)values[i]) != CodeTypes.NotUsed)
codeTypes.Add(cType);
helperCodeTypes.Add(cType);
}
}
}
And Models.AggregationLevelConfiguration is:
public class AggregationLevelConfiguration
{
public byte AggregationLevelConfigurationId { get; set; }
public int ProductionOrderId { get; set; }
public string Name { get; set; }
public byte CodeType { get; set; }
public byte HelperCodeType { get; set; }
public int PkgRatio { get; set; }
public int RemainingCodes { get; set; }
}
I need to set selected value in these properties:
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
But I can't set it in new SelectList(codeTypes, "Id", "Name"); or new SelectList(helperCodeTypes, "Id", "Name"); because the selected value are in Configurations array: fields AggregationLevelConfiguration.CodeType and AggregationLevelConfiguration.HelperCodeType.
I think I have to set selected value in the View, but I don't know how to do it.
How can I set the selected values?
Unfortunately #Html.DropDownListFor() behaves a little differently than other helpers when rendering controls in a loop. This has been previously reported as an issue on CodePlex (not sure if its a bug or just a limitation)
The are 2 option to solve this to ensure the correct option is selected based on the model property
Option 1 (using an EditorTemplate)
Create a custom EditorTemplate for the type in the collection. Create a partial in /Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml (note the name must match the name of the type
#model yourAssembly.AggregationLevelConfiguration
#Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // other properties of AggregationLevelConfiguration
and then in the main view, pass the SelectList to the EditorTemplate as additionalViewData
#using (Html.BeginForm())
{
...
#Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems })
...
Option 2 (generate a new SelectList in each iteration and set the selectedValue)
In this option your property CodeTypeItems should to be IEnumerable<GenericIdNameType>, not a SelectList (or just make codeTypes a public property). Then in the main view
#Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType)
Side note: there is no need to use new { id = "Configurations[0].HelperCodeType" - the DropDownListFor() method already generated that id attribute
I wrote this class to overcome an issue I was having with selecting an option in an html select list. I hope it helps someone.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Login_page.Models
{
public class HTMLSelect
{
public string id { get; set; }
public IEnumerable<string> #class { get; set; }
public string name { get; set; }
public Boolean required { get; set; }
public string size { get; set; }
public IEnumerable<SelectOption> SelectOptions { get; set; }
public HTMLSelect(IEnumerable<SelectOption> options)
{
}
public HTMLSelect(string id, string name)
{
this.id = id;
this.name = name;
}
public HTMLSelect(string id, string name, bool required, IEnumerable<SelectOption> options)
{
this.id = id;
this.name = name;
this.required = required;
}
private string BuildOpeningTag()
{
StringBuilder text = new StringBuilder();
text.Append("<select");
text.Append(this.id != null ? " id=" + '"' + this.id + '"' : "");
text.Append(this.name != null ? " name=" + '"' + this.name + '"' : "");
text.Append(">");
return text.ToString();
}
public string GenerateSelect(IEnumerable<SelectOption> options)
{
StringBuilder selectElement = new StringBuilder();
selectElement.Append(this.BuildOpeningTag());
foreach (SelectOption option in options)
{
StringBuilder text = new StringBuilder();
text.Append("\t");
text.Append("<option value=" + '"' + option.Value + '"');
text.Append(option.Selected != false ? " selected=" + '"' + "selected" + '"' + ">" : ">");
text.Append(option.Text);
text.Append("</option>");
selectElement.Append(text.ToString());
}
selectElement.Append("</select");
return selectElement.ToString();
}
}
public class SelectOption
{
public string Text { get; set; }
public Boolean Selected { get; set; }
public string Value { get; set; }
}
}
And
public IEnumerable<SelectOption> getOrderTypes()
{
List<SelectOption> orderTypes = new List<SelectOption>();
if (this.orderType == "OptionText")
{
orderTypes.Add(new SelectOption() { Value = "1", Text = "OptionText", Selected = true });
} else
{
orderTypes.Add(new SelectOption() { Value = "2", Text = "OptionText2" });
}
}
And to use it:
#{
Login_page.Models.HTMLSelect selectElement = new Login_page.Models.HTMLSelect("order-types", "order-types");
}
#Html.Raw(selectElement.GenerateSelect(Model.getOrderTypes()));
I leave this in case it helps someone else. I had a very similar problem and none of the answers helped.
We had in a view this line at the top:
IEnumerable<SelectListItem> exitFromTrustDeed = (ViewData["ExitFromTrustDeed"] as IEnumerable<string>).Select(e => new SelectListItem() {
Value = e,
Text = e,
Selected = Model.ExitFromTrustDeed == e
});
and then below in the view:
#Html.DropDownListFor(m => m.ExitFromTrustDeed, exitFromTrustDeed, new { #class = "form-control" })
We had a property in my ViewData with the same name as the selector for the lambda expression and for some reason that makes the dropdown to be rendered without any option selected.
We changed the name in ViewData to ViewData["ExitFromTrustDeed2"] and that made it work as expected.
Weird though.

Viewmodel nested checkbox not binding on post

I have a subscription form that contains a matrix of options. The form can be seen in screenshot Subscription table
I am having trouble with ASP.NET MVC generating appropriate ID's and then on postback having the binder populate the model with the form selections.
The add on name is down the left side and when posted back the collection of SubscriptionInputModel.Addons get populated ok. But SubscriptionInputModel.Addons[i].SubscriptionLevelCombos is null as seen in debug screenshot
The current code is using CheckBoxFor but I've also tried manually generating ID's in format:
#Html.CheckBox("addon[" + a + "].SubscriptionLevelCombo[" + i + "].AddonSelected", addon.SubscriptionLevelCombos[i].AddonSelected)
Neither format has worked and also experimented while debugging but no luck. I would appreciate any ideas. Worst case I assume I would need to read the raw form collection?
I assume the level of nested object shouldn't matter as it is all object path notation and array indexes in html tag names?
Here are snippets of current code to help illustrate what exists.
View Models
public class SubscriptionInputModel
{
//other stuff to come
//....
//add on's, listed down left of table
public List<SubscriptionInputAddonModel> Addons;
}
public class SubscriptionInputAddonModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Note { get; set; }
public List<SubscriptionInputAddonComboModel> SubscriptionLevelCombos { get; set; }
}
public class SubscriptionInputAddonComboModel
{
public int? Id { get; set; }
public decimal? AddonCost { get; set; }
public CostTimeUnitOption? CostTimeUnit { get; set; }
public bool? IsComplimentaryBySubscriptionLevel { get; set; }
public string ComboText { get; set; }
public bool AddonSelected { get; set; }
public int? AddonId { get; set; }
}
SubscriptionController
[Route("identity/subscription")]
// GET: Subscription
public ActionResult Index()
{
SubscriptionInputModel model = new SubscriptionInputModel();
ArrbOneDbContext db = new ArrbOneDbContext();
List<SubscriptionInputAddonModel> addons = Mapper.Map<Addon[], List<SubscriptionInputAddonModel>>(db.Addons.OrderBy(a => a.OrderPosition).ToArray());
model.Addons = addons;
foreach(var addon in model.Addons)
{
var addonCombos = db.Database.SqlQuery<SubscriptionInputAddonComboModel>(#"SELECT SLA.Id, AddonCost, CostTimeUnit, IsComplimentaryBySubscriptionLevel, ComboText, AddonId
FROM SubscriptionLevel L
LEFT OUTER JOIN SubscriptionLevelAddon SLA ON L.Id = SLA.SubscriptionLevelId AND SLA.AddonId = #p0
ORDER BY L.OrderPosition", addon.Id);
addon.SubscriptionLevelCombos = addonCombos.ToList();
}
return View(model);
}
[Route("identity/subscription")]
[ValidateAntiForgeryToken]
[HttpPost]
// POST: Subscription
public ActionResult Index(SubscriptionInputModel model)
{
ArrbOneDbContext db = new ArrbOneDbContext();
List<SubscriptionInputAddonModel> addons = Mapper.Map<Addon[], List<SubscriptionInputAddonModel>>(db.Addons.OrderBy(a => a.OrderPosition).ToArray());
model.Addons = addons;
//debug breakpoint to inspect returned model values
return View();
}
Index.cshtml
#model Identity_Server._Code.ViewModel.Subscription.SubscriptionInputModel
#{
ViewBag.Title = "Subscription";
}
#using (Html.BeginForm("Index", "Subscription", new { signin = Request.QueryString["signin"] }, FormMethod.Post))
{
#Html.ValidationSummary("Please correct the following errors")
#Html.AntiForgeryToken()
...
// ADD ONs ----------------------------------------------------------------------------------
#for (int a = 0; a < Model.Addons.Count; a++)
{
var addon = Model.Addons[a];
<tr>
<td class="text-left">#addon.Name
<div class="SubscriptionItemNote">#addon.Note
#Html.HiddenFor(m => m.Addons[a].Id)
</div>
</td>
#for (int i = 0; i < addon.SubscriptionLevelCombos.Count; i++)
{
<td>
#if (addon.SubscriptionLevelCombos[i].Id.HasValue)
{
if (addon.SubscriptionLevelCombos[i].AddonCost.HasValue && addon.SubscriptionLevelCombos[i].AddonCost.Value > 0)
{
#Html.Raw("<div>+ " + #addon.SubscriptionLevelCombos[i].AddonCost.Value.ToString("0.##") + " / " + #addon.SubscriptionLevelCombos[i].CostTimeUnit.Value.ToString() + "</div>")
}
else if (addon.SubscriptionLevelCombos[i].IsComplimentaryBySubscriptionLevel.HasValue && #addon.SubscriptionLevelCombos[i].IsComplimentaryBySubscriptionLevel.Value)
{
<span class="glyphicon glyphicon-ok"></span>
}
if (!string.IsNullOrEmpty(addon.SubscriptionLevelCombos[i].ComboText))
{
<div>#addon.SubscriptionLevelCombos[i].ComboText</div>
}
if (addon.SubscriptionLevelCombos[i].AddonCost.HasValue && addon.SubscriptionLevelCombos[i].AddonCost.Value > 0)
{
#Html.HiddenFor(m => m.Addons[a].SubscriptionLevelCombos[i].Id)
#Html.CheckBoxFor(m => m.Addons[a].SubscriptionLevelCombos[i].AddonSelected)
}
}
</td>
}
</tr>
}

How to show sum using LINQ statement in Grid view of the MVC app

I developing the MVC application.
I am stuck in LINQ Syntax.
I wan to show the sum of List Items in index view of parent.
Please check code below.
In Model I have two classes.
public class StockAdjustment
{
public int Id { get; set; }
public List<StockAdjustmentItem> StockAdjustmentItems { get; set; }
public int SumOfStockAdjustmentItemQuantity
{
get
{
if (this.StockAdjustmentItems != null)
{
return this.StockAdjustmentItems.Sum(s=>s.OriginalQuantity);
}
return 0;
}
}
}
public class StockAdjustmentItem
{
public int Id { get; set; }
public int OriginalQuantity { get; set; }
public StockAdjustment StockAdjustment { get; set; }
}
public StockAdjustment GetAll(int Id)
{
oStockAdjustment = GetStockAdjustmentById(Id);
var prepo = new ProductRepo();
oStockAdjustment.StockAdjustmentItems = new List<StockAdjustmentItem>();
StockAdjustmentItem ai1 = new StockAdjustmentItem();
ai1.Id = 1 ;
ai1.OriginalQuantity = 250;
oStockAdjustment.StockAdjustmentItems.Add(ai1);
StockAdjustmentItem ai2 = new StockAdjustmentItem();
ai2.Id = 1;
ai2.OriginalQuantity = 375;
oStockAdjustment.StockAdjustmentItems.Add(ai2);
return oStockAdjustment;
}
Now I have controller Code
public ActionResult Index(string searchContent = "")
{
AdjustmentRepo oAdjustmentRepo = new AdjustmentRepo();
var adjustments = from adjustment in oAdjustmentRepo.GetAll() select adjustment;
ViewBag.StockAdjustmentList = adjustments;
return View(adjustments);
}
This Working perfectly fine...
Now, the problem comes when, I am trying to show StockAdjustment in List.
I have to show the sum of the OriginalQuantites of StockAdjustmentItems in the Front of StockAdjustment item in grid.
in above Exmaple I want to show 650(250 + 375) in the row of a gird.
#model IEnumerable<StockWatchServices.DomainClass.StockAdjustment>
#Html.Grid(Model).Columns(columns =>
{
columns.Add(c=>c.StockAdjustmentItems.Sum( OriginalQuantity ???? Im stuck here... )
}
What should I write here ?
I can see like this...
Create a getter only property on the StockAdjustment class
public class StockAdjustment
{
public int Id { get; set; }
public List<StockAdjustmentItem> StockAdjustmentItems { get; set; }
public int SumOfStockAdjustmentItemQuantity
{
get
{
if (this.StockAdjustmentItems != null)
{
return this.StockAdjustmentItems.Sum(s=>s.OriginalQuantity);
}
return 0;
}
}
}
And then in your Razor view:
#Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.SumOfStockAdjustmentItemQuantity)
}
Can you try with below code :
#Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.StockAdjustmentItems.Where(quantity => quantity.OriginalQuantity != null).Sum(sum => sum.OriginalQuantity).ToString());
})

Model Item type ambiguity when using PagedList

I am developing a web survey application in ASP.Net Mvc3. I use PagedList in my application to paginate the questions page alone.
I get the following error:
The model item passed into the dictionary is of type
'PagedList.PagedList`1[SWSSMVC.Models.ViewModels.QuestionViewModel]',
but this dictionary requires a model item of type
'PagedList.IPagedList`1[SWSSMVC.Models.ViewModels.QuestionListViewModel]'.
There is a question which is of similar nature. The solution says not to specify anonymous type, as far as I understood. Can someone point out where in my code I have anonymous type? I believe I have typed all my variables with appropriate models.
This is the question Controller:
public class QuestionController : SessionController
{
DBManager dbmgr = new DBManager();
//
// GET: /Question/
public ActionResult Index(string currentSection, string currentPage, int? page)
{
int j;
SectionSession = currentSection;
PageSession = currentPage;
var questionList = new QuestionListViewModel();
int questionCount = dbmgr.getQuestionCount(currentPage);
var question = new QuestionViewModel();
for(int i=1 ; i<=questionCount; i++)
{
int questionid = dbmgr.getQuestionid(currentPage, i);
string questiontext = dbmgr.getQuestion(questionid);
List<string> oldchoices = dbmgr.getChoicesAns(questionid);
ChoiceViewModel choice = new ChoiceViewModel();
question = new QuestionViewModel { QuestionId = questionid, QuestionText = questiontext, Answer = oldchoices.Last()};
for (j = 0; j < oldchoices.Count() - 1; j++)
{
if (oldchoices[j] != null)
{
question.Choices.Add(new ChoiceViewModel { ChoiceId = j, ChoiceText = oldchoices[j] });
}
}
questionList.Questions.Add(question);
}
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(questionList.Questions.ToPagedList(pageNumber, pageSize));
}
There are two models:
public class QuestionViewModel
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public List<ChoiceViewModel> Choices { get; set; }
public string Answer { get; set; }
[Required]
public string SelectedAnswer { get; set; }
public QuestionViewModel()
{
Choices = new List<ChoiceViewModel>();
}
}
public class QuestionListViewModel
{
public List<QuestionViewModel> Questions { set; get; }
public QuestionListViewModel()
{
Questions = new List<QuestionViewModel>();
}
}
I am entering my part- Index View code for the above Question Controller
#model PagedList.IPagedList<SWSSMVC.Models.ViewModels.QuestionListViewModel>
#{
ViewBag.Title = "Index";
}
<h2>Questions</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
#foreach (var item in Model)
{
#Html.EditorFor(x => item.Questions)
}
I also have a Editor Template like this
#model SWSSMVC.Models.ViewModels.QuestionViewModel
<div>
#Html.HiddenFor(x => x.QuestionId)
<h3> #Model.QuestionText </h3>
#foreach (var a in Model.Choices)
{
<p>
#Html.RadioButtonFor(b => b.SelectedAnswer, a.ChoiceText) #a.ChoiceText
</p>
}
</div>
I tried to run through the code a couple of times and having hard time figuring it out. I also do not know how I could have made the questionList as a LINQ variable, given that, my questionList is inturn constructed with questions and choices from a separate model.
Creator of PagedList here. The problem is that this line:
return View(questionList.Questions.ToPagedList(pageNumber, pageSize));
Is sending a model of type IPagedList down to the page (because the extension method is being applied to a type of List), but your page says it is expecting:
#model PagedList.IPagedList<SWSSMVC.Models.ViewModels.QuestionListViewModel>
Changing your view code to say this instead should fix it:
#model PagedList.IPagedList<SWSSMVC.Models.ViewModels.QuestionViewModel>

Placing a list of values into a viewmodel in ASP.Net MVC

I'm getting myself completely confused, and would appreciate if anyone can point me in the right direction again.
I am trying to add a search form to a ficticious project, for my own learning purposes.
Idea is - I have a Date text box, and a number of days hire text box - when search is hit - the code should look for all cars that have been booked between the date entered, and the date plus the number of days hire required. (A)
This will generate a list of cars which have to be excluded from the next part of the search (B)
It then searches for Cars (C), and excludes the list generated at (B)
The Linq then populates the ct object (D) freeCarTypes.
freeCarTypes at this point, correctly holds the data I'm looking for - a list of:
Car Type (TypeNme)
Type ID
TypeCount (how many of this car type are available)
NumSelected (set to 0 by default)
NumSelected (I'm hoping) will be populated in the model, when I list each car type, with a drop down list of the TypeCount (available) - which will then populate the NumSelected part of the model. so when the post happens, I have a list of car types, and the number of each type the Dealer is interested in.
My problem is, how do I get the List of cars - freeCarTypes (D) - into my SearchViewModel.TypesAvail?
Is it my SearchViewModel using IQueryable that is wrong, or should I be using something else here - I'm going round in circles.
Thanks for any help,
Mark
public class SearchViewModel
{
[Required]
public DateTime From { get; set; }
[Required]
public int Days { get; set; }
public long DealerID { get; set; }
public IQueryable<Car> Cars { get; set; }
public IQueryable<TypesAvail> TypesAvails { get; set; }
}
public class TypesAvail
{
public String TypeNme { get; set; }
public long TypeID { get; set; }
public int TypeCount { get; set; }
public int NumSelected { get; set; }
}
My SearchController
[HttpPost]
public ActionResult Avail(SearchViewModel model, string id)
{
if (ModelState.IsValid)
{
// (A)
var dteFrom = model.From;
var dteTo = model.From.AddDays(model.Nights);
// (B)
var prebookedCars = db.Cars
.Where(car => car.Rentals.Any(rental =>
(model.DealerID == rental.Dealer_id) && (
(dteFrom >= rental.dateout && dteFrom < rental.dateback)
||
(dteTo > rental.dateout && dteTo <= rental.dateback)
||
(dteFrom <= rental.dateout && dteTo >= rental.dateback)
)));
// (C)
var freeCarTypes = db.Cars
.Where(r => r.DealerID == model.DealerID)
.Except(prebookedCars)
.GroupBy(p => p.CarType)
.Select(ct => new // (D)
{
TypeNme = ct.Key.type_name,
TypeID = ct.Key.type_id,
TypeCount = ct.Count(),
NumSelected = 0
}
);
foreach (var fr in freeCarTypes)
{
TypesAvail ta = new TypesAvail();
{
ta.NumSelected = fr.NumSelected;
ta.TypeCount = fr.TypeCount;
ta.TypeID = fr.TypeID;
ta.TypeNme = fr.TypeNme;
}
}
// This is where I'm stuck - how do I get the list above, into the ViewModel, to I can generate a list of car types, with a drop down list of how many are available
// model.TypesAvail = ta;
// model.TypesAvail = freeCarTypes;
return View(model);
}
else // model is not valid, so return the View
{
return View(model);
}
}
How about this?
// (C)
model.TypesAvail = db.Cars.Where(r => r.DealerID == model.DealerID)
.Except(prebookedCars)
.GroupBy(p => p.CarType)
.Select(ct => new TypesAvail // (D)
{
TypeNme = ct.Key.type_name,
TypeID = ct.Key.type_id,
TypeCount = ct.Count(),
NumSelected = 0
};

Resources