Using DropDownList(For) with model binding on nested class - c#

I am relying heavily on EditorTemplates in my application, but I've run into a problem which I can not seem to solve, without not moving away from EditorTemplates for drop down lists.
Consider this (View)Model:
public class CreateStudentViewModel
{
public DropDownList StudentTypes { get; set; }
public CreateStudent Command { get; set; }
}
public class DropDownList {
public string SelectedValue { get; set; }
public IList<SelectListItem> Items { get; set; }
}
public class CreateStudent {
public string Name { get; set; }
public int StudentTypeId { get; set; }
}
I use this to provide a way for the frontend user to set the student type, this is done with the following EditorTemplate:
#model DropDownList
<div class="form-group#(Html.ValidationErrorFor(m => m.SelectedValue, " has-error"))">
#Html.LabelFor(m => m)
#Html.DropDownListFor(m => m.SelectedValue, Model.Items)
#Html.ValidationMessageFor(m => m.SelectedValue, null)
</div>
And used within my view:
#Html.EditorFor(m => m.StudentTypes)
Now this EditorTemplate is binding to the StudentTypes.SelectedValue on DropDownList, which is good in some cases - but I need to bind this to my Model.Command.StudentTypeId here.
I know I can move all this code directly to the view and directly bind it, instead of having it inside a EditorTemplate, but I will try my best to avoid this.
Ideally I am thinking of extending the EditorFor to provide a way like:
#Html.EditorFor(m => m.StudentTypes, new { selectedValue = Model.Command.StudentTypeId });
But I can not seem to translate this to something like:
#Html.DropDownList(#ViewBag.selectedValue.ToString(), Model.Items);
As this just places the value (int) as the field name. Any suggestions is welcome! :-)

Your chief problem here is encapsulating your drop down list in a class in order to rely on the C# type editor template convention. Instead, just use your model directly and use UIHint to tell Razor to use a particular template. Here's a simplified version of what I use:
View Model
[UIHint("Choice")]
public int SelectedFoo { get; set; }
public IEnumerable<SelectListItem> FooChoices { get; set; }
Views\Shared\EditorTemplates\Choice.cshtml
#{
var choices = ViewData["choices"] as IEnumerable<SelectListItem> ?? new List<SelectListItem>();
if (typeof(System.Collections.IEnumerable).IsAssignableFrom(ViewData.ModelMetadata.ModelType) && ViewData.ModelMetadata.ModelType != typeof(string))
{
#Html.ListBox("", choices)
}
else
{
#Html.DropDownList("", choices)
}
}
View
#Html.EditorFor(m => m.SelectedFoo, new { choices = Model.FooChoices })
In case it's not obvious, the conditional in the editor template determines if the property is a value or list type, and either uses a drop down list control or listbox control, respectively.

Related

asp.net mvc multiple dropdrownlist

I have a form that loads some Partial Views dinamically and one of these Partial Views will load multiple dropdownlists in the screen.
I have a ViewModel (principal): used in the main view
public class CupomFiscalDetalhesViewModel
{
//some properties
public IEnumerable<CupomItensViewModel> CupomItens { get; set; }
}
An intermediate ViewModel: the view model of the partial view:
public class CupomItensViewModel
{
public IEnumerable<TabelaPrecoViewModel> TabelasPreco { get; set; }
public TabelaPrecoViewModel TabelaPrecoSelecionada { get; set; }
}
Where TabelaPrecos is holding the values that I want to show in the DropDownList. and TabelaPrecoSelecionada will hold the selected value.
In the Controller, I'm used to put the values of an IEnumerable into a ViewBag, and use this ViewBag to generate the dropdownlist in the HTML, like this:
ViewBag.TabelaPrecoSelecionada = new SelectList
(
detalhesCupomFiscal.CupomItens.FirstOrDefault().TabelasPreco,
"IdTabela",
"NomeTabela"
);
But I have no idea how to generate multiple dropdowns for each option of CupomItensViewModel, without passing the id of the selected value of each dropdownlist to the controller action (by parameter).
In the Html, I use: but would need to change the name to get binding workin somehow.
#Html.DropDownList("TabelaPrecoSelecionada",(IEnumerable<SelectListItem>)ViewBag.TabelaPrecoSelecionada,
new { #class = "form-control dropdown" })
Does anyone has an Idea how to accomplish it?
I haven't test this but I would maybe create the select list inside your CupomItensViewModel
using System.Linq;
public class CupomItensViewModel
{
public IEnumerable<TabelaPrecoViewModel> TabelasPreco { get; set; }
public TabelaPrecoViewModel TabelaPrecoSelecionada { get; set; }
public IEnumerable<SelectListItem> TabelasPrecoSelectList
{
get
{
return TabelasPreco.Select(x => new SelectListItem()
{
Value = x.IdTabela
Text = x.NomeTabela
Selected = TabelaPrecoSelecionada.IdTabela
}
}
}
}
And Inside your view
#foreach(var item in Model.CupomItens)
{
#Html.DropDownList("TabelaPrecoSelecionada", item.TabelasPrecoSelectList, new { #class = "form-control dropdown" })
}
But if these dropdowns aren't going to be next to each other, I would make
public IEnumerable<CupomItensViewModel> CupomItens { get; set; }
List instead and using index to identify them. CupomItens[x]
Just my 2 cent without checking if it works. Hopefully it helps.

MVC 5 ViewModel with EditorTemplate of a enumerable property

I'm trying to find the best correct way to do the following:
I have a ViewModel for a character editor called CharacterViewModel. This CharacterViewModel is populated with a Character object, a list of available ability scores a character can have, which are in another table.
I created an edit template for the drop down, and I'm trying to find a way to recuperate the list of edited abilities. I can't seem to get them back on the controller.
Here is the ViewModel code:
public class CharacterViewModel : DbContext
{
public Character Character { get; set; }
[UIHint("CharacterAbilityScores")]
public IEnumerable<CharacterAbilityScore> CharacterAbilityScores { get; set; }
public IEnumerable<SelectListItem> AbilityScoresSelectList { get; set; }
public IEnumerable<AbilityModifiersAndBonusSpellDTO> AbilityModifiersAndBonusSpellDTO { get; set; }
public CharacterViewModel()
: base("name=CharacterModels")
{
}
}
Here is the controller code for populating the ViewModel:
public async Task<ActionResult> Edit(int? id)
{
Character character = db.Characters.Find(id);
var model = new CharacterViewModel();
model.Character = character;
model.CharacterAbilityScores = character.CharacterAbilityScores;
// Creating the list of ability scores for the view
model.AbilityScoresSelectList = from amabs in db.AbilityModifiersAndBonusSpells
select new SelectListItem()
{
Value = amabs.score.ToString(),
Text = amabs.score.ToString()
};
return View(model);
}
The edit method signature in the controller (the CharacterAbilityScores property and the other complex ones are always empty on the return trip):
public async Task<ActionResult> Edit(CharacterViewModel characterViewModel)
Here is the related code in the edit view:
#model CampaignManager.Models.CharacterViewModel
#using (Html.BeginForm())
{
<div class="form-group">
#Html.EditorFor(model => model.CharacterAbilityScores, new { AbilityScoresSelectList = Model.AbilityScoresSelectList })
</div>
}
And finally, the EditorTemplate:
#model IEnumerable<CampaignManager.Entities.CharacterAbilityScore>
<table>
#foreach (var abilityScore in Model)
{
<tr>
<td>#abilityScore.Ability.Abbreviation</td>
<td>
#{
if (ViewData["AbilityScoresSelectList"] != null)
{
#Html.HiddenFor(z => abilityScore);
#Html.HiddenFor(z => abilityScore.AbilityId);
#Html.DropDownListFor(x => abilityScore.AbilityId, (IEnumerable<SelectListItem>)ViewData["AbilityScoresSelectList"], dropDownHTMLOptions);
}
}
</td>
<tr>
}
</table>
I've tried many different HiddenFor tricks, storing the whole collection, storing different id's... I'm a bit lost in there I'll admit. Maybe I'm doing this all wrong and I need another approach?
UPDATE
Here is the model for the CharacterAbilityScore entity:
public partial class CharacterAbilityScore
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CharacterId { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int AbilityId { get; set; }
public int AbilityScore { get; set; }
public virtual Ability Ability { get; set; }
public virtual AbilityModifiersAndBonusSpell AbilityModifiersAndBonusSpell { get; set; }
public virtual Character Character { get; set; }
}
EditorFor() is designed to wok with collection where the EditorTemplate is the type in the collection (in your case you have made the EditorTemplate's model a collection (not the type) and are then giving each element a duplicate id attribute (invalid html) and duplicate name attributes (which cant be bound to a collection).
Change the template (Views/Shared/EditorTemplates/CharacterAbilityScore.cshtml) to:
#model CampaignManager.Entities.CharacterAbilityScore
<tr>
<td>#Html.DisplatFor(m => m.Ability.Abbreviation)</td>
<td>#Html.DropDownListFor(m => m.AbilityId, (IEnumerable<SelectListItem>)ViewData["AbilityScoresSelectList"])</td>
</tr>
and in the main view
#model CampaignManager.Models.CharacterViewModel
#using (Html.BeginForm())
{
<table>
#Html.EditorFor(model => model.CharacterAbilityScores, new { AbilityScoresSelectList = Model.AbilityScoresSelectList })
</table>
}
Side notes:
You have not posted the model for CharacterAbilityScore so a have
assumed it contains properties Abbreviation (for display only) and
AbilityId (associated with the dropdown).
You can not use #Html.HiddenFor() on a complex object (the value
will be the .ToString() output of the object) and having
#Html.HiddenFor() for the same property as the dropdown (and
located before #Html.DropDownListFor()) means that you will bind
to the hidden input on post back (i.e. the original value, not the
selected value from the dropdown)
I also recommend your view models do not derive from DbContext.
The purpose of a view model is to define the properties you want to
display/edit in the view

#Html.DropDownList returns null when submitted

I have here a scenario. I want to make an HTTP POST action in the form so here's how I did it.
public class Item
{
public Item()
{
Storages = new HashSet<Storage>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Storage> Storages { get; set; }
-- remove some lines for brevity --
}
public class Storage
{
public int Id { get; set; }
public string Name { get; set; }
--- remove some lines for brevity --
}
So basically, An Item has many Storage And so I created viewmodel.
public class CreateStockViewModel
{
public string Name { get; set; }
public int StorageId { get; set; }
-- remove some lines for brevity --
}
In my Controller. I have this
[HttpGet]
public ActionResult Create()
{
ViewBag.Storages = _storageService.All
.OrderBy(i => i.Name)
.ToSelectList(s => s.Name, s => s.Id);
return View();
}
In my View:
#model Wsfis.Web.ViewModels.ItemViewModels.CreateStockViewModel
#Html.DropDownList("Storages")
Now my problem is, when I submit the form. And have Quick Watch to the model being passed. It is Null or 0
public ActionResult Create(CreateStockViewModel item)
{
// some code
}
In a nutshell,
When I submit the form all fields are being bind except for the #Html.DropDownList. Where did I missed?
Some additional side note:
They say Views should be strongly typed. Then what should I pass in View then? (A sample code would be great. Thanks)
As for the ToSelectList method I copy this code (I hope it's alright)
Any help would be much appreciated. Thanks.
Your form input has a different name to your property so the default model binder doesn't know how to bind your model.
You could pass in a different name to use to the DropDownList helper, however I prefer to use the strongly typed helpers:
#Html.DropDownListFor(m => m.StorageId, ViewBag.Storages as IEnumerable<SelectListItem>)
Try like this:
ViewBag.StorageId = _storageService.All
.OrderBy(i => i.Name)
.ToSelectList(s => s.Name, s => s.Id);
in view:
#Html.DropDownList("StorageId")
it will now post the drop down list selected value in CreateStockViewModel object's StorageId property.

initializing an empty view model

i am trying to initialize an empty view model with a drop down property in it so when it comes to controller, it doesnt give error about the dropdown. Below is the code how I am trying to get it to work but it skips over the foreach loop because the model is empty at the start:
ExampleViewModel
public class ExampleViewModel
{
public ExampleViewModel()
{
ExampleViewModel = new ExampleViewModel();
}
public SelectList dropdown{ get; set; }
public string dropdownvalue { get; set; }
}
}
Controller code:
List<ExampleViewModel > integration = new List<ExampleViewModel >();
foreach (var item in ExampleViewModel )
{
item.dropdown= ApplicationService.GetDropdownlist(null);
}
In View my drop down is being called as:
#Html.LabelFor(model => model.dropdown, new { #id = "rightlabel" })
<span>
#Html.DropDownListFor(model => model.dropdownvalue, Model.dropdown)
#Html.ValidationMessageFor(model => model.dropdown)
</span>
is there a possible workaround this so dropdown list gets initialised ?
You seem to be Initialising a variable that does not exist and not initialising the properties that you actually care about..
public class ExampleViewModel
{
public ExampleViewModel()
{
this.dropdown = new List<string>();
this.dropdownvalue = string.Empty;
}
public List<string> dropdown{ get; set; }
public string dropdownvalue { get; set; }
}
}
That will stop null reference exceptions. I would also not place a SelectList in a view model... a List would be much better.
You should construct the SelectList in your view using the List from the view model... replace List<> with something more appropriate depending on your requirements.

MVC3 View Model - List of Complex Objects, containing Lists

How do I bind such a complex model with multiple layers that contain multiple objects?
Right now I pass the model to the view - (populating a form / a check box tree) and I would like the exact model back (SubjectSelectionModel) but it's not binding correctly.
Could anyone elaborate on the process I need to take in order to bind these correctly in my view?
View Model:
public class SubjectSelectionModel
{
public IList<Subject> Subjects { get; set; }
}
Subject Class:
public class Subject
{
public String Name { get; set; }
public IList<Bin> Bins { get; set; }
public Subject()
{
}
public Subject(IList<Course> courses)
{
}
}
Bin Class:
public class Bin
{
public Subject Subject { get; set; }
public int Amount { get; set; }
public IList<Foo> Foos { get; set; }
}
Foo Class:
public class Foo
{
public int Number { get; set; }
}
This is where Editor Templates come in handy. Rather than messing around with this, you can use simple editor templates to handle all the grunt work for you.
You would create several templates in ~/Views/Shared/EditorTemplates, and then in your primary view it should look like this:
View.cshtml
#model SubjectSelectionModel
#using(Html.BeginForm()) {
#EditorFor(m => m.Subjects)
<input type="submit" />
}
Subject.cshtml
#model Subject
#Html.EditorFor(m => m.Name)
#Html.EditorFor(m => m.Bins)
Bin.cshtml (I assume you don't want to render Subject, this would be an infinite loop)
#model Bin
#Html.EditorFor(m => m.Amount)
#Html.EditorFor(m => m.Foos)
Foo.cshtml
#model Foo
#Html.EditorFor(m => m.Number)
Obviously, you may want to change the html formatting to whatever you want, but that's essentially it.
You need a for loop for the objects so MVC can bind using the index in the collection.
Example:
for (int subjectIndex = 0; subjectIndex < Model.Subjects.Count; subjectIndex++) {
#Html.TextBoxFor(x => x.Subjects[subjectIndex].Name)
for (int binIndex = 0; binIndex < Model.Subjects.Bins.Count; binIndex++) {
#Html.TextBoxFor(x => x.Subjects[subjectIndex].Bins[binIndex].Amount)
}
}
..etc.
I gave a similar response to a similar question, here: Generating an MVC RadioButton list in a loop

Categories