Grouping in for loop razor view - c#

I Have the following in my razor view
#foreach (var group in Model.QuestionList.GroupBy(x => x.AreaName))
{
<h4>#group.Key</h4>
for (int i = 0; i < Model.QuestionList.Count(x => x.AreaName == group.Key); i++)
{
<div class="form-group">
<div class="row">
<div class="col-md-4">
#Html.DisplayFor(x => Model.QuestionList[i].Question)
</div>
<div class="col-md-2">
#Html.HiddenFor(x => Model.QuestionList[i].StnAssureQuestionId)
#Html.DropDownListFor(model => model.QuestionList[i].Score, new SelectList(Model.QuestionList[i].Scores, "ScoreId", "ScoreNum", 0), "Please Select", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.QuestionList[i].Score, "", new { #class = "text-danger" })
</div>
<div class="col-md-4">
#Html.EditorFor(x => Model.QuestionList[i].Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.QuestionList[i].Comments, "", new { #class = "text-danger" })
</div>
</div>
</div>
}
}
I want to be able to display all the objects in QuestionList but group them by AreaName, which is the group key.
The current code displays the title of the first group then the questions in that group but after that all it does is display the next group name followed by the same questions then again for all the group.
It's a no brainer I'm sure but I'm still not skilled enough to spot it.

You might be able to get by with something like this, but I'd take other's advice about creating a specific view model for this view also.
#foreach (var group in Model.QuestionList.GroupBy(x => x.AreaName))
{
var questionList = group.ToList();
<h4>#group.Key</h4>
for (int i = 0; i < questionList.Count(); i++)
{
<div class="form-group">
<div class="row">
<div class="col-md-4">
#Html.DisplayFor(x => questionList[i].Question)
</div>
<div class="col-md-2">
#Html.HiddenFor(x => questionList[i].StnAssureQuestionId)
#Html.DropDownListFor(model => questionList[i].Score, new SelectList(questionList[i].Scores, "ScoreId", "ScoreNum", questionList[i].Score), "Please Select", new { #class = "form-control" })
#Html.ValidationMessageFor(model => questionList[i].Score, "", new { #class = "text-danger" })
</div>
<div class="col-md-4">
#Html.EditorFor(x => questionList[i].Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => questionList[i].Comments, "", new { #class = "text-danger" })
</div>
</div>
</div>
}
}
Dot Net Fiddle Example

You should not be using complex queries in your view, and while the JamieD77's answer will solve the issue of correctly displaying the items, it will fail to bind to your model when you submit.
If you inspect the html you generating you will see that for each group you have inputs such as
<input type="hidden" name="questionList[0].StnAssureQuestionId" ... />
<input type="hidden" name="questionList[1].StnAssureQuestionId" ... />
but the DefaultModelBinder requires collection indexers to start at zero and be consecutive so when binding, it will correctly bind the inputs in the first group, but ignore those in all other groups because the indexers starts back at zero.
As always start with view models to represent waht you want to display/edit (What is ViewModel in MVC?). In this case I'm assuming the SelectList options associated with Score are common across all Questions
public class QuestionnaireVM
{
public IEnumerable<QuestionGroupVM> Groups { get; set; }
public SelectList Scores { get; set; }
}
public class QuestionGroupVM
{
public string Name { get; set; }
public IEnumerable<QuestionVM> Questions { get; set; }
}
public class QuestionVM
{
public int ID { get; set; }
public string Question { get; set; }
public int Score { get; set; }
public string Comments { get; set; }
}
While you could use nested loops in the view
for (int i = 0; i < Model.Groups.Count; i++)
{
<h4>Model.Groups[i].Name</h4>
for (int j = 0; j < Model.Groups[i].Count; j++)
{
#Html.DisplayFor(m => m.Groups[i].Questions[j].Question)
a better solution is to use EditorTemplates which give you a reusable component (and you would not have to change the collection properties to IList<T>). Note I have omitted <div> elements to keep it simple.
In /Views/Shared/EditorTemplates/QuestionVM.cshtml
#model QuestionVM
#Html.DisplayFor(m => m.Question)
#Html.HiddenFor(m => m.ID)
#Html.DropDownListFor(m => m.Score, (SelectList)ViewData["scores"], "Please Select", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Score, "", new { #class = "text-danger" })
#Html.EditorFor(m => m.Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(m => m.Comments, "", new { #class = "text-danger" })
In /Views/Shared/EditorTemplates/QuestionGroupVM.cshtml
#model QuestionGroupVM
<h4>#Html.DisplayFor(m => m.Name)</h4>
#Html.EditorFor(m => m.Questions, new { scores = ViewData["scores"] })
and the main view would be
#model QuestionnaireVM
#using (Html.BeginForm())
{
#Html.EditorFor(m => m.Groups, new { scores = Model.Scores })
<input type="submit" value="Save" />
}
Then in the get method, project your data model to the view model, for example
QuestionnaireVM model = new QuestionnaireVM
{
Groups = db.Questions.GroupBy(x => x.AreaName).Select(x => new QuestionGroupVM
{
Name = x.Key,
Questions = x.Select(y => new QuestionVM
{
ID = y.StnAssureQuestionId,
Question = y.Question,
Score = y.Score,
Comments = y.Comments
}
},
Scores = new SelectList(.....)
};
return View(model);
and the signature of the POST method would be
public ActionResult Edit(QuestionnaireVM model)
Side note: You do not currently have an input for the group name property which means if you needed to return the view because ModelState was invalid, you would need to run the query again, so consider adding #Html.HiddenFor(m => m.Name) to the QuestionGroupVM.cshtml template (and of course if you do retur the view, you also need to reassign the SelectList property.

When you displaying your questions you should work with your group object (grouped collection) but not with the initial collection.
I mean you should change your
Model.QuestionList[i]
To
group.Select(x => x.QuestionList)[i]
Anyway your solution really messy It's better to do such grouping on server side.

Please consider that a View should be completely agnostic to the business logic implemented by the service layer. View is just a dummy presentation mechanism which grabs data served by a Controller through a ViewModel and displays the data. It is the basic of the MVC architecture and my strong recommendation is that following the architecture is itself a very good reason to go the right way.
That being said the view you have is getting messy. Consider reconstructing it as something like this:
public class QuestionDataViewModel
{
public List<QuestionData> Data { get; set; }
}
public class QuestionData
{
public string AreaName { get; set; }
public List<Question> QuestionList { get; set; }
}
public class Question
{
public int StnAssureQuestionId { get; set; }
public int Score { get; set; }
public IEnumerable<SelectListItem> Scores { get; set; }
public List<Comment> Comments { get; set; }
}
Construct this server side and just render through simple razor foreach loops. This will not only benefit you with cleaner code but will also help avoid the model binding pain you are about to run into when you post the form back with your current implementation.

Related

c# Razor View Html ValidationMessageFor CheckboxList at least one checked

I have the following ViewModel on my MVC project:
public class CustomViewModel
{
//more properties
public List<CustomCheckbox> CheckBoxList { get; set; }
}
The CustomCheckbox class is like this:
public string value { get; set; }
public bool isChecked {get; set;}
Then on my View I use the following Form creating a list of Checkbox:
#using (Html.BeginForm("Create", "CustomController", FormMethod.Post, new { id ="customId"}))
{
<div class="form-group mb30 mt-2">
#Html.LabelFor(model => model.CustomCheckbox, "Checkbox", htmlAttributes: new { #class = "control-label col-md-2 form-label" })
<div class="col-md-10 select-div">
#for (int i = 0; i < Model.CustomCheckbox.Count; i++)
{
<span class="frequence-checkbox">
#Html.CheckBoxFor(m => m.CustomCheckbox[i].isChecked)
#Html.LabelFor(m => m.CustomCheckbox[i].isChecked, Model.CustomCheckbox[i].value)
#Html.HiddenFor(m => m.CustomCheckbox[i].value)
</span>
}
#Html.ValidationMessageFor(model => model.CustomCheckbox, "", new { #class = "text-danger" })
</div>
</div>
}
The problem is that I'm not being able to activate the ValidationMessageFor to check if at least one checkbox is checked.
I know I need to add a Required annotation to the property on the ViewModel but there's no one to validate properties from a list.
Any ideas?

Asp.net MVC multiple select for List property

I'm fairly new to ASP.Net MVC so forgive me for anything that should just be obvious.
I have an object that contains a property that is a list. I only don't know how I should implement this in the create.
this is the object:
public class TeamMember
{
public int TeamMemberId { get; set; }
public string FristName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string Biographie { get; set; }
public virtual Image Image { get; set; }
public virtual List<DanGrade> DanGrades { get; set; }
}
In the create view I want to be able to select multiple Dangrades.
I tried to modify an editor Template for it that looks like this:
#using BudoschoolTonNeuhaus.Models
#model BudoschoolTonNeuhaus.Models.TeamMember
#{
var db = new ApplicationDbContext();
var danGrades = db.DanGrades.ToList();
}
<select multiple name="#ViewData.TemplateInfo.HtmlFieldPrefix" class="dropdown">
#foreach (var dan in danGrades)
{
<option value="#">
#dan.DanGradeId: #dan.BudoSport, #dan.Grade
</option>
}
</select>
but this does not give the result that I thought it would, its just showing mutiple dangrade labels in the create view that you can see here:
#model BudoschoolTonNeuhaus.Models.TeamMember
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Admin_Layout.cshtml";
}
<div class="wrapper">
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>TeamMember</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FristName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FristName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FristName, "", new { #class = "text-danger" })
</div>
</div>
.... // controls for other properties of model
<div class="form-group">
#Html.LabelFor(model => model.DanGrades, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DanGrades, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DanGrades, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="Image" name="Image" hidden />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
current HTML output:
Thanks for you help in advance!
To create a <select multiple> you use the ListBoxFor() method in your view.
But your model needs two properties to generate a listbox, a IEnumerable<int> to bind the selected values to (assumes the ID proeprty of DanGrade is typeof int), and an IEnumerable<SelectListItem> to display the <option> elements.
You editing data, so always start with a view model
public class TeamMemberVM
{
public int? TeamMemberId { get; set; }
....
[Display(Name = "DanGrades")]
public IEnumerable<int> SelectedDanGrades { get; set; }
public IEnumerable<SelectListItem> DanGradesList { get; set; }
}
and your view will be
#model yourAssembly.TeamMemberVM
....
#Html.ListBoxFor(m => m.SelectedDanGrades, Model.DanGradesList, new { #class="dropdown" })
and your controller methods will be
public ActionResult Create()
{
TeamMemberVM model = new TeamMemberVM();
ConfigureViewModel(model);
// For an Edit method, your would set the existing selected items here
model.SelectedDanGrades = ...
return View(model);
}
public ActionResult Create(TeamMemberVM model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model); // repopulate the SelectList
return View(model);
}
// model.SelectedDanGrades contains the ID's of the selected options
// Initialize an instance of your data model, set its properties based on the view model
// Save and redirect
}
private void ConfigureViewModel(TeamMemberVM model)
{
IEnumerable<DanGrade> danGrades = db.DanGrades();
model.DanGradesList = danGrades.Select(x => new SelectListItem
{
Value = x.DanGradeId.ToString(),
Text = x.??? // the name of the property you want to use for the display text
});
}
Note also that your view has a file input so your view model needs a HttpPostedFileBase property to bind the file to
public HttpPostedFileBase Image { get; set; }
and in the view
#Html.TextBoxFor(m => m.Image, { new type ="file" })
Shouldn't your model be like that ?
[UIHint("NameOfTheEditorTemplate")]
public virtual List<DanGrade> DanGrades { get; set; }
Be sure to put the EditorTemplate under one of these two paths
~/Views/Shared/EditorTemplates
~/Views/Controller_Name/EditorTemplates
As explained in this post
So you are trying to save a list of custom objects inside your object. First of all, know that if you try to save teammember to a database your list of objects will not save. I've experienced this same issue and its needs some special configuring to get just that to work.
Second you can't select custom objects from a < select >. Select returns string[] to your controller. So objects, no. You can't return complex items like that using select directly.
What you can do is return a string[] and use the individual strings (maybe it contains name, maybe it contains id?) and then use that array to pull each object to your teammember object in the controller from the dangrade db context (I'm assuming that is where they are stored).
So for example if you Go back to your controller and add (string[] dangrades) to your parameters. Your parameters now looks something like this (string[] dangrades, Bind[blahblah] ... teammember).
Now after referencing the other database you can do as follows
teammember.Dangrades = new list<Dangrade>();
foreach(string item in dangrades)
{
var dangradeselected = from x in db.dangrades where x.name = item select x;
var dangradefromlinq = dangradeselected.tolist();
teammember.Dangrades.Add(dangradefromlinq[0]);
}
If you had previously stored dangrades in some other format (ie not a database) then you will have to append your code, or ask specifically with that for a better answer.
Also don't forget to give your select and id= (lookup html attributes) so that the controller can recognize it.
You can probably make this (pseudo)code a little neater. Also don't forget about possible null values.
If you want to save a list of items for each teamember you can also look into having 2 databases. I'm not sure if this is recommended. But you can have one for teammembers, and one for dangrades. In the case of dangrades you would add an additional property called grouping id that would match the id of your teammember. So when you pull up your teammember you could also pull up all related dawngrades that match its database id.
That's everything I can think of. If you find a simpler solution by all means go with that.

DropDownList doesn't want to be set

My dropDown list doesn't want to have default value!
<div class="form-group">
#Html.LabelFor(model => model.unit, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.unit.id, selectUnit)
#Html.ValidationMessageFor(model => model.unit.id, "", new { #class = "text-danger" })
</div>
</div>
Show me the right list but none is selected.
I get my SelectList by using ViewBag:
#{
IEnumerable<SelectListItem> selectUnit = ViewBag.Unit;
}
When I breakpoint the cshtml, Model.unit.id is 4 and selectUnit have one item with 4 as value.
When I do
#selectUnit.Where(x => x.Value == Model.unit.id.ToString()).First().Text
it selects the right text value!
Lats think: this is my Unit model:
public class Unit
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public IList<Unit> children { get; set; }
}
Thanks in advance folks, I'm becoming crasy
EDIT:
public class ModelPassedTroughTheView
{
...
public Unit unit { get; set; }
}
EDIT 2: Full code:
Edit page:
#model BE.DealerGroupSAP
#{
ViewBag.Title = Resources.Admin.DealerGroup_Edit;
IEnumerable<SelectListItem> selectUnit = ViewBag.Unit;
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>#ViewBag.Title</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.id)
<div class="form-group">
#Html.LabelFor(model => model.unit, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.unit.id, selectUnit)
#Html.ValidationMessageFor(model => model.unit.id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="#Resources.Global.Save_Edits" class="btn btn-default" />
</div>
</div>
</div>
}
Model passer trough view:
public class DealerGroupSAP
{
public int id { get; set; }
public Unit unit { get; set; }
}
Unit object:
public class Unit
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public IList<Unit> children { get; set; }
}
Controller's content:
ViewBag.Unit = GetUnits();
return View(BL.AnomalyBL.GetAllSAPResponsible(id));
The issue is that your model has a property named unit and your also passing the SelectList view a ViewBag property named Unit (the model binding features of MVC are case insensitive.
Change the name of the ViewBag property to (say)
ViewBag.UnitList = GetUnits();
and in the view
#{ IEnumerable<SelectListItem> selectUnit = ViewBag.UnitList }
and the correct option will be selected.
To explain what is happening internally:
The DropDownListFor() method determines the defaultValue (selected item) by first checking values in ModelState (which in your case do not exist), then checking ViewData. Because ViewData contains a key/value pair for Unit, which is IEnumerable<SelectListItem> and does not contain a property id, the defaultValue is nulland the method uses the IEnumerable<SelectListItem> you passed to the view to build the <option> elements, none of which have a Selected = true value, so the first option is selected because something has to be.
Changing the ViewBag property to to (say) UnitList means the method does not find a matching key for unit in ViewData and now inspects the model for unit.id, which exists, and sets defaultValue = 4. Because defaultValue is not null, a new IEnumerable<SelectListItem> is generated internally, and the corresponding SelectListItem has its Selected property set to true.
To understand how this all works in detail, you can inspect the source code for SelectExtensions - in particular the private static MvcHtmlString SelectInternal() method.
As a final note, this is just one more reason why you should always use a view model.

ASP.NET MVC EditorTemplate not being used

I am currently making a website in ASP.NET MVC where i would like to use EditorTemplates to display a List inside my ViewModel. RowViewModel has a List of RowDataViewModels. I'm trying to make a Create View for RowViewModel, where i can use
#Html.EditorFor(model => model.RowData)
and therefore i need an EditorTemplate. I created and EditorTemplate under:
Views/Shared/EditorTemplates/RowDataViewModel.cshtml
And i also tried putting the EditorTemplates folder under the /Home/ view folder, but nothing seems to work. No breakpoints are being hit inside the editortemplate. I think i did it this way before, but i might be forgetting something.
Any ideas?
RowViewModel:
public class RowViewModel
{
[Required]
[Display(Name="Name")]
public string Name { get; set; }
public List<RowDataViewModel> RowData { get; set; }
}
RowDataViewModel:
public class RowDataViewModel
{
public string Name { get; set; }
public string Value { get; set; }
public string DataType { get; set; }
}
EditorTemplate - RowDataViewModel.cshtml:
#using iDealWebRole.ViewModels
#model RowDataViewModel
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Value, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Value, "", new { #class = "text-danger" })
</div>
</div>
The problem is here: #Html.EditorFor(model => model.RowData)
You should use your editor for every row in RowData, like:
#for (int i = 0; i < Model.RowData.Count(); i++)
{
#Html.EditorFor(model => Model.RowData[i])
}

Creating and editing a collection of strings using MVC3

Having some trouble understanding how to create and edit a collection of strings using a form. I've tried using EditorFor but it seems to have no luck and instead puts the following text into the form. I'm trying to edit the collection "Keywords".
System.Collections.Generic.HashSet`1[MVCModuleStarter.Models.Module]System.Collections.Generic.HashSet`1[MVCModuleStarter.Models.Module]
This is the Html I'm using the EditorFor in with a working EditorFor being used on a string for reference.
<div class="form-group">
#Html.LabelFor(model => model.Category, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Category, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Category, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Keywords, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Keywords, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Keywords, "", new { #class = "text-danger" })
</div>
</div>
This is the Edit method inside my controller;
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ModuleId,ModuleTitle,ModuleLeader,ModuleDescription,ImageURL,Category,Keywords")] Module module)
{
if (ModelState.IsValid)
{
int moduleId = module.ModuleId;
repository.UpdateModule(module);
repository.Save();
return RedirectToAction("Details", new { Id = moduleId });
}
return View(module);
}
This is the Model for reference;
[Required, StringLength(20), Display(Name = "Category")]
public string Category { get; set; }
public virtual ICollection<Keyword> Keywords { get; set; }
Model for Keyword
public class Keyword
{
[Key, Display(Name = "ID")]
public int KeywordId { get; set; }
[Required, StringLength(100), Display(Name = "Keyword")]
public string KeywordTerm { get; set; }
public virtual ICollection<Module> Modules { get; set; }
}
}
Any help would be amazing, still new to this! Thanks!
You need to create an EditorTemplate for Keyword, for example
In /Views/Shared/EditorTemplates/Keyword.cshtml (add divs, class names etc as required)
#model Keyword
#Html.HiddenFor(m => m.KeywordId)
#Html.LabelFor(m => m.KeywordTerm)
#Html.TextBoxFor(m => m.KeywordTerm)
#Html.ValidationMessageFor(m => m.KeywordTerm)
Then in the main view
Html.EditorFor(m=> m.Keywords)
Note I have omitted the collection property Modules, but if you also want to edit them, the add another EditorTemplate for Modules
Alternatively you can use a for loop in the main view. This would mean the collection need to be IList<T>
for(int i = 0; i < Model.Keywords.Count, i++)
{
#Html.HiddenFor(m => m.Keywords[i].KeywordId)
// other properties of Keyword
for (int j = 0; j < Model.Keywords[i].Modules.Count; j++)
{
#Html.TextBoxFor(m => m.Keywords[i].Modules[j].SomeProperty)
// other properties of Module
}
}

Categories

Resources