DropDownList doesn't want to be set - c#

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.

Related

Use two models in one form (view) - ASP.NET MVC

In my form, which I created in a view, the user can press add or search.
If the "add" button is pressed, a different model should be used in the background than with the "search" option. The add model is validated but otherwise does not differ from the search model.
By clicking "search" the user shouldn't be forced to fill in all fields.
Code
Model - AddModel
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Name")]
[StringLength(200, MinimumLength = 1, ErrorMessage = "Not Allowed")]
public string Name { get; set; }
[Required]
[Display(Name = "Place")]
[RegularExpression(#"^[\w ]*$", ErrorMessage = "Not Allowed")]
public string Place { get; set; }
Model - SearchModel
public int Id { get; set; }
public string Name { get; set; }
public string Place{ get; set; }
Controller
[HttpPost, ValidateAntiForgeryToken]
public IActionResult Add(AddModel p) {
if (ModelState.IsValid) {
_ = InsertData(p);
ModelState.Clear();
return RedirectToAction("Add", new { Success = true });
}
return View();
}
public IActionResult Select(SearchModel p)
{
Task.WaitAll(SelectData(p));
return View(per); // per => list of selected data
}
View
#model **AddModel**
#if (ViewBag.success)
{
...
}
<form method="POST">
<div class="form-group">
#Html.LabelFor(m => m.Name, new { })
#Html.EditorFor(m => m.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(m => m.Name, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Place, new { })
#Html.EditorFor(m => m.Place, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(m => m.Place, "", new { #class = "text-danger" })
</div>
<input asp-action="Add" type="submit" class="btn btn-outline-primary" value="Add" />
<input asp-action="Select" type="submit" class="btn btn-outline-success" value="Search" />
</form>
The AddModel is still used in the View, but I would like to specify in the controller which model I would like to use. So if you press "search" the SearchModel and with "add" the AddModel should be used. I've already tried it with dynamic, but then it came to problems with the #html helpers.
Does somebody has any idea?
Would appreciate ;)
I think what you are looking to do is called a ViewModel, this should help : https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-3

Update ViewModel after dynamically updating the view

I am trying to define ViewModels that faithfully represent the view (to make strict use of that concept).
Some of the elements of the ViewModel are updated dynamically. The problem I have, is that when I do the Post, the ViewModel returns without the elements that were updated dynamically.
The update is done through jQuery, when an event is performed. An action is invoked through Url.Action, and a Div is updated.
I made an example to clarify the scenario. An application that only stores a location (state and city). For this I have three ViewModels: one to represent the States in a SelectList, one to represent the Cities in a SelectList, and finally one to represent the Location (formed by the two ViewModel that I mentioned first).
Models:
public class State
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
public class City
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int StateId { get; set; }
public virtual State State { get; set; }
}
ViewModels:
public class CitySelectListViewModel
{
public CitySelectListViewModel() { }
public CitySelectListViewModel(IEnumerable<Models.City> cities)
{
this.Cities = cities;
}
[Display(Name = "Cities")]
[Required]
public int? SelectedCityId { get; set; }
public IEnumerable<City> Cities { get; }
}
public class StateSelectListViewModel
{
public StateSelectListViewModel() { }
public StateSelectListViewModel(IEnumerable<State> states)
{
this.States = states;
}
[Display(Name = "States")]
[Required]
public int? SelectedStateId { get; set; }
public IEnumerable<State> States { get; }
}
public class LocationCreateViewModel
{
public LocationCreateViewModel() { }
public LocationCreateViewModel(ICollection<State> states)
{
this.StateSelectListViewModels = new StateSelectListViewModel(states);
this.CitySelectListViewModel = new CitySelectListViewModel();
}
public StateSelectListViewModel StateSelectListViewModels { set; get; }
public CitySelectListViewModel CitySelectListViewModel { set; get; }
}
Location [Controller]:
public class LocationController : Controller
{
private DALDbContext db = new DALDbContext();
// GET: Location/Create
public ActionResult Create()
{
LocationCreateViewModel locationCreateViewModel = new LocationCreateViewModel(db.States.ToList());
return View(locationCreateViewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(LocationCreateViewModel pLocationCreateViewModel)
{
if (ModelState.IsValid)
{
//db.States.Add(state);
//db.SaveChanges();
return RedirectToAction("Index", "Home");
}
LocationCreateViewModel locationCreateViewModel = new LocationCreateViewModel(db.States.ToList());
return View(locationCreateViewModel);
}
public ActionResult CitySelectList(int? stateId)
{
CitySelectListViewModel citySelectListViewModel = new CitySelectListViewModel(db.Cities.Where(c => c.StateId == stateId).ToList());
return View(citySelectListViewModel);
}
}
Create [View]:
#model ViewModelExample.ViewModels.LocationCreateViewModel
....
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>State</h4>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.StateSelectListViewModels.SelectedStateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateSelectListViewModels.SelectedStateId, new SelectList(Model.StateSelectListViewModels.States, "Id", "Name"), "Select a State", htmlAttributes: new { #class = "form-control", #id = "StateSelectList" })
#Html.ValidationMessageFor(model => model.StateSelectListViewModels.SelectedStateId, "", new { #class = "text-danger" })
</div>
</div>
<div id="CityContainer">
#Html.Action("CitySelectList")
</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>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
// Fill City DropDownList
$('#StateSelectList').change(function () {
var selectedStateId = this.value;
$('#CityContainer').load('#Url.Action("CitySelectList")?stateId=' + selectedStateId);
});
});
</script>
}
CitySelectList [View]:
#model ViewModelExample.ViewModels.CitySelectListViewModel
....
<div class="form-group">
#Html.LabelFor(model => model.SelectedCityId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SelectedCityId, new SelectList(Model.Cities, "Id", "Name"), "Select a City", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SelectedCityId, "", new { #class = "text-danger" })
</div>
</div>
I will show the execution of my example, and I will show the problem through the inspection of the ViewModel that I receive after the Post:
I select a State and a City, and I press Create.
I inspect the ViewModel received after the Post. We can see how CitySelectListViewModel is null, and what I want is to bring the last ViewModel that was updated through jQuery.
I admit that I have provided a long example, but it is the only way I found to explain what I need. Thanks in advance.
VS-Project of the example
I'ts because you are preventing the modelBinder to accurately bind to LocationCreateViewModel in your Create action when replacing the inner HTML of <div id="CityContainer"> (thats what you do with $('#CityContainer').load(...). You instruct the model binder to bind to
#model ViewModelExample.ViewModels.CitySelectListViewModel and as a result you get this HTML for the city select list:
One way of solving this is modifying CitySelectList.cshtml to:
#model ViewModelExample.ViewModels.LocationCreateViewModel
#{
Layout = null;
}
<div class="form-group">
#Html.LabelFor(model => model.CitySelectListViewModel.SelectedCityId,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model =>
model.CitySelectListViewModel.SelectedCityId, new
SelectList(Model.CitySelectListViewModel.Cities, "Id", "Name"), "Select a City", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CitySelectListViewModel.SelectedCityId, "", new { #class = "text-danger" })
</div>
</div>
and your CitySelectList action to:
public ActionResult CitySelectList(int? stateId)
{
LocationCreateViewModel locationCreateViewModel = new LocationCreateViewModel();
locationCreateViewModel.CitySelectListViewModel = new CitySelectListViewModel(db.Cities.Where(c => c.StateId == stateId).ToList());
return View(locationCreateViewModel);
}
But I would recommend custom model binding as well.

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.

Grouping in for loop razor view

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.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'PestType'

I am learning MVC and Entity Framework, so pleas bear my questions... I am trying to create a drop down menu for a property (Enum type) for my model class SinglePest
Here is the model:
public class SinglePest
{
public int SinglePestId { get; set; }
public PestType PestType { get; set; } // here is my problem
public string Alias { get; set; }
public string TechName { get; set; }
public string Markings { get; set; }
public string SerialNumber { get; set; }
public SourceType SourceType { get; set; }
//virtual property
public Source Source { get; set; }
}
Here is PestType:
public enum PestType
{
Dog,
Cat,
Fox,
Rabbit,
Rat
}
This is the controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create (//(SinglePest singlepest)
[Bind(Include= "Alias, TechName, SerialNumber, PestType, Markings")] SinglePest singlepest)
{
try
{
if (ModelState.IsValid)
{
db.SinglePests.Add(singlepest);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException /* dex */)
{
ModelState.AddModelError("", "Unable to save changes, try again, if problem persits contact your administrator");
}
//ViewBag.SerialNumber = new SelectList(db.Sources, "SerialNumber", "SerialNumber", singlepest.SerialNumber);
return View(singlepest);
}
And here is the View where I get the error (There is no ViewData item of type 'IEnumerable' that has the key 'PestType'.) :
<div class="editor-label">
#Html.LabelFor(model => model.PestType, "Pest Type")
</div>
<div class="editor-field">
#Html.DropDownList("PestType", String.Empty) // here is the error
#Html.ValidationMessageFor(model => model.PestType.ToString())
</div>
Now I have seen some posts about displaying enum, but I can't figure out a solution for my problem. Could please someone give me some piece of advice on how to fix it?
Thank you for your time!
You have #Html.DropDownList("PestType", String.Empty), but the second param needs to be an IEnumerable<T>. You will need the list of your pest in the model, and then use model.Pests for example where Pets is an IEnumerable.
EDIT: Based on comment...
But I want to display just the various types of pest (Dog, Cat, etc)
not all the pests that are in my database
OK, are these categorised, could you write something like (hand written so check syntax)..
var pests = (from _context.Pests.Where(p => p.CategoryId == 1) select p.PestName).ToList();
If you need to get a IEnumerable for the enum (since I'm not sure what the DB looks like), you can use...
Enum.GetValues(typeof(PestType))
.OfType<PestType>()
.Where(p => p == ??);
Currently your model only contains a place to store the value and not a Array/IEnumerable to populate the drop down from.
First add an IEnumerable to your model:
public class SinglePest
{
public int SinglePestId { get; set; }
public IEnumerable<PestType> Pests { get; set; }
public PestType PestType { get; set; }
public string Alias { get; set; }
public string TechName { get; set; }
public string Markings { get; set; }
public string SerialNumber { get; set; }
public SourceType SourceType { get; set; }
//virtual property
public Source Source { get; set; }
}
And in your controller:
public ActionResult Create()
{
var model = new SinglePest();
model.Pests = Enum.GetValues(typeof(PestType)).Cast<PestType>()
return View(model);
}
And your view:
#Html.DropDownListFor(m => m.PestType, Model.Pests);
Sorry if theres any errors I've written this from memory...
I found this post on DropDownListFor enums
It seems it is solving my problem.
so I have just changed the view with this new piece of code:
<div class="editor-label">
#Html.LabelFor(model => model.PestType, "Pest Type")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.PestType, new SelectList(Enum.GetValues(typeof( MvcTrackingSystem.Enums.PestType))))
#Html.ValidationMessageFor(model => model.PestType)
</div>
Now it looks like it is working
On the difference between DropDownList and DropDownListFor I have found useful infromation on this post
You can fix the original problem quite simply with this in your GET Create method:
ViewBag.PestType = new SelectList(Enum.GetValues(typeof(PestType)).OfType<PestType>());
and this in your POST Create method (where validation fails and it returns the view):
ViewBag.PestType = new SelectList(Enum.GetValues(typeof(PestType)).OfType<PestType>(),
singlepest.PestType);
if you want to keep it strongly typed in the view use:
#Html.DropDownListFor(model => model.PestType, ViewBag.PestType as SelectList)
If you don't mind the weak typed version use the simpler:
#Html.DropDownList("PestType")
In either case I suggest you create all lists in the controller and not in the view.
Explanation:
Basically DropDownlist will search the ViewData (i.e. your ViewBag settings) for a list of options for the member of the same name (if a list is not explicitly provided).
I mocked up the whole project (MVC5/VS2013) and more of the code is below for your reference.
Controller:
using PestTypeTest.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PestTypeTest.Controllers
{
public class PestTypeController : Controller
{
//
// GET: /PestType/
public ActionResult Index()
{
return RedirectToAction("Create");
}
public ActionResult Create()
{
ViewBag.PestType = new SelectList(Enum.GetValues(typeof(PestType)).OfType<PestType>());
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(//(SinglePest singlepest)
[Bind(Include = "Alias, TechName, SerialNumber, PestType, Markings")] SinglePest singlepest)
{
try
{
if (ModelState.IsValid)
{
//db.SinglePests.Add(singlepest);
//db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException /* dex */)
{
ModelState.AddModelError("", "Unable to save changes, try again, if problem persits contact your administrator");
}
//ViewBag.SerialNumber = new SelectList(db.Sources, "SerialNumber", "SerialNumber", singlepest.SerialNumber);
ViewBag.PestType = new SelectList(Enum.GetValues(typeof(PestType)).OfType<PestType>(), singlepest.PestType);
return View(singlepest);
}
}
}
Views\PestType\Create.cshtml
#model PestTypeTest.Models.SinglePest
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SinglePest</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.PestType, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("PestType")
#Html.ValidationMessageFor(model => model.PestType)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Alias, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Alias)
#Html.ValidationMessageFor(model => model.Alias)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TechName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TechName)
#Html.ValidationMessageFor(model => model.TechName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Markings, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Markings)
#Html.ValidationMessageFor(model => model.Markings)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SerialNumber, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SerialNumber)
#Html.ValidationMessageFor(model => model.SerialNumber)
</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>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

Categories

Resources