Bind DropDownListFor with List on ViewModel - c#

I'm trying to do this:
This is my ViewModel and Model:
public class OpeningYearViewModel
{
public int OpeningYearId { get; set; }
public string Description { get; set; }
public List<Grade> GradesList { get; set; }
}
public class Grade
{
public int GradeId { get; set; }
public string Name { get; set; }
public int CurrencyId { get; set; }
public int Cost { get; set; }
}
This is my Controller. I build a SelecList here and pass it to the view through the ViewBag
OpeningYearViewModel viewmodel = new OpeningYearViewModel {
OpeningYearId = 1,
Description = "2015 - II",
GradesList = new List<Grade>
{
new Grade { GradeId = 1, Name = "Grade 1", CurrencyId = 1, Cost = 100 },
new Grade { GradeId = 2, Name = "Grade 2", CurrencyId = 2, Cost = 200 },
new Grade { GradeId = 3, Name = "Grade 3", CurrencyId = 2, Cost = 150 }
}
};
SelectList list = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Text = "S/.", Value = "1"},
new SelectListItem { Text = "$", Value = "2"},
}, "Value" , "Text");
ViewBag.currencyList = list;
return View(viewmodel);
And in my View I need a DropDownListFor for every item on GradesList so I do this:
#model Test.Models.OpeningYearViewModel
#for(int i = 0; i < Model.GradesList.Count; i++)
{
#Html.DropDownListFor(x => x.GradesList[i].CurrencyId, new SelectList(ViewBag.currencyList, "Value", "Text"))
#Model.GradesList[i].CurrencyId //This is just to know the CurrencyId on every item.
}
I'm getting every select correctly rendered, but I can't get the correct option selected on the page load:
render of view
It is possible to do what I'm trying to do and I'm doing something wrong, or DropDownListFor works in a different way?
Thanks!

I can't understand why this is happening but you can workaround it by setting explicitly the selected value. This can be done by passing Model.GradesList[i].CurrencyId as fourth parameter to the SelectList's constructor:
#for(int i = 0; i < Model.GradesList.Count; i++)
{
#Html.DropDownListFor(x => x.GradesList[i].CurrencyId,
new SelectList(ViewBag.currencyList, "Value", "Text", Model.GradesList[i].CurrencyId))
}

Since, the DropDownListFor is used in loop to generate indexed inputs; so generate input controls will be generated with name as "GradeList[0].CurrencyId", "GradeList[1].CurrencyId"......Due to this framework will not bind the selected value in Select List as it is unable to get the value in reflection for selection. That's why you have to use the following SelectList constructor to set the selected value.
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
object selectedValue
)
However, if your DropDownListFor is bind to a simple expression like
#Html.DropDownListFor(model => model.CurrencyId, new SelectList(ViewBag.Items, "Value", "Text"))
then selection will work automatically.

Related

MultiSelectList multiple values not working

I have this MultipleSelectList in my view:
#Html.ListBoxFor(s => s.Id,
new MultiSelectList((IEnumerable<SelectListItem>)ViewData["ddlList"], "Value", "Text", Model.Id),
new { #style = "margin-top:250px", multiple = "multiple" })
This list is populated here
#{
using (var b = new Entity())
{
ViewData["ddlList"] = b.Table.Select(e => new SelectListItem()
{
Value = e.Id.ToString(),
Text = e.Name
}).ToList();
}
}
This is my model
public string Name { get; set; }
public int[] Id { get; set; }
The problem is that when I select multiple options, only the first one gets to my controller like this:
int[] value = modelObj.Id;
modelObj.Id;--stores my selected values
Someone knows how can I solve this?
Selected values will be array of string not array of int. So, change the type of Id property to type of string[]:
public string[] Id { get; set; }

Set selected value in dropdownlist from MVC Controller

I am binding a dropdownlist using the below code
Model
public IEnumerable<TitleNew> TitleOption =
new List<TitleNew>
{
new TitleNew {Id = 0, Value = "---Select---"},
new TitleNew {Id = 1, Value = "Mr."},
new TitleNew {Id = 2, Value = "Ms."}
};
public class TitleNew
{
public int Id { get; set; }
public string Value { get; set; }
}
public string Title { get; set; }
View
#Html.DropDownListFor(m => m.Title,
new SelectList(Model.TitleOption,
"Id", "Value",
Model.TitleOption.First().Id))
I was unable to set the selected value to dropdownlist. The selected value comes from the database and it sets for Title property.
Please help me out.
new TitleNew {Id = 0, Value = "---Select---"} looks like an option label, which is already included in an overloaded method for dropdownlistfor.
So if you want that to be the option that all users first see when they look at the dropdownlist then this should work:
public IEnumerable<TitleNew> TitleOption =
new List<TitleNew>
{
new TitleNew {Id = 0, Value = "Mr."},
new TitleNew {Id = 1, Value = "Ms."}
};
public class TitleNew
{
public int Id { get; set; }
public string Value { get; set; }
}
public string Title { get; set; }
View:
#Html.DropDownListFor(m => m.Title, new SelectList(Model.TitleOption, "Id", "Value"), "-- Select -- ")

ViewModel replacement for complex Anonymous Object

So im working with this complex anonymous object
var result = new
{
percentage = "hide",
bullets = (string)null,
item = new [] {
new {
value = 16,
text = "Day",
prefix = (string)null,
label = (string)null
},
new {
value = 41,
text = "Week",
prefix = (string)null,
label = (string)null
},
new {
value = 366,
text = "Month",
prefix = (string)null,
label = (string)null
}
}
};
And I want to convert it into a ViewModel and return it as JSON from a rest API.
What I would like to know is
How do I represent this as a model including the array item entries
How do I then add array items to the array once an instance of the model is created
Does the model need a constructor to initialize the array.
Any help or examples you could provide would be great.
Create a class with the structure:
public class Result
{
public Result()
{
// initialize collection
Items = new List<Item>();
}
public string Percentage { get; set; }
public string Bullets { get; set; }
public IList<Item> Items { get; set; }
}
public class Item
{
public int Value { get; set; }
public string Text { get; set; }
public string Prefix { get; set; }
public string Label { get; set; }
}
Then change your code to this:
var result = new Result
{
Percentage = "hide",
Bullets = (string)null,
Items = {
new Item {
Value = 16,
Text = "Day",
Prefix = (string)null,
Label = (string)null
},
new Item {
Value = 41,
Text = "Week",
Prefix = (string)null,
Label = (string)null
},
new Item {
Value = 366,
Text = "Month",
Prefix = (string)null,
Label = (string)null
}
}
};
Addressed above with the structure.
Add to collection as follows:
result.Items.Add(new Item {
Value = 367,
Text = "Month",
Prefix = (string)null,
Label = (string)null
});
I would initialize the collection in the constructor as above.
To return the json from your controller action add the following:
return Json(result, JsonRequestBehavior.AllowGet);

creating a drop down list in MVC5

I am trying to create a drop down list but it gives me an error saying 'Cannot implicitly convert type 'string' to 'System.Web.Mvc.SelectList'. My code is below:
Application Database Model:
public string dropdown{ get; set; }
Application View Model:
public SelectList dropdown{ get; set; }
ApplicationService.cs:
public static SelectList GetDropdownList(string currSelection)
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Value = "1", Text = "firstvalue" });
list.Add(new SelectListItem { Value = "2", Text = "secondvalure" });
list.Add(new SelectListItem { Value = "3", Text = "All of the Above" });
return new SelectList(list, "Value", "Text", currSelection);
}
in my controller i am calling:
applicationviewmodel.dropdown= ApplicationService.GetDropdownList(null);
and then trying to save it in database as:
ApplicationDatabaseModel.dropdown= applicationviewmodel.dropdown;
This is where i get this error.
In my view i have:
#Html.DropDownListFor(x => x.dropdown, applicationviewmodel.dropdown)
I am not sure how to make this work.
I find it's easier to just have a List as part of your model and use a simple linq statement. Simple example below for a countries drop down:
assuming you have a model like
public class MyModel()
{
public int CountryId { get; set; }
public List<Country> Countries { get; set; }
}
and a Country class of
public class Country()
{
public int Id { get; set; }
public string Name { get; set; }
}
in your view you can then do the following:
#Html.DropDownListFor(m => m.CountryId,
Model.Countries.Select(x =>
new SelectListItem { Text = x.Name, Value = x.Id.ToString(), Selected = Model.CountryId == x.Id }, "Please Select...", null)
This:
#Html.DropDownListFor(x => x.dropdown, applicationviewmodel.dropdown)
..is incorrect. It is trying to store the selected item into the SelectList instance.
What you want is a string variable on the view model that this value is selected into:
public class ApplicationViewModel {
public SelectList DropDown { get; set; }
public string SelectedDropDownValue { get; set; }
// .. the rest of the properties here
}
Then your view becomes this:
#Html.DropDownListFor(x => x.SelectedDropDownValue, Model.DropDown)
This says "store the selected value into SelectedDropDownValue".
Then, you need to change how you build your SelectList. Value is what gets posted to your property.. Text is what is displayed in the browser.
So this:
list.Add(new SelectListItem { Value = "1", Text = "firstvalue" });
list.Add(new SelectListItem { Value = "2", Text = "secondvalure" });
list.Add(new SelectListItem { Value = "3", Text = "All of the Above" });
..has to be this:
list.Add(new SelectListItem { Value = "firstvalue", Text = "firstvalue" });
list.Add(new SelectListItem { Value = "secondvalue", Text = "secondvalure" });
list.Add(new SelectListItem { Value = "all of the above", Text = "All of the Above" });
..because they are strings (unless of course, you want the numbers to be posted back).
Then, finally, your controller code becomes this:
// assign the string value to the string property
ApplicationDatabaseModel.dropdown = applicationviewmodel.SelectedDropDownValue;

DropDownList SelectList SelectedValue issue [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I get this ASP.NET MVC SelectList to work?
What the hell is it? Is there some kind of a bug in DropDownList of MVC3?
SelectedValue doesn't show up as actually selected in the markup.
I am trying different approaches, nothing works.
public class SessionCategory
{
public int Id { get; set; }
public string Name { get; set; }
}
public static IEnumerable<SessionCategory> Categories
{
get
{
var _dal = new DataLayer();
return _dal.GetSesionCategories();
}
}
#{
var cats = Infrastructure.ViewModels.Session.Categories;
var sl = new SelectList(cats, "Id", "Name",2);
}
#Html.DropDownList("categories", sl);
Try the following:
Model:
public class MyViewModel
{
public int CategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
Controller:
public ActionResult Foo()
{
var cats = _dal.GetSesionCategories();
var model = new MyViewModel
{
// Preselect the category with id 2
CategoryId = 2,
// Ensure that cats has an item with id = 2
Categories = cats.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Name
})
};
}
View:
#Html.DropDownListFor(
x => x.CategoryId,
new SelectList(Model.Categories, "Value", "Text")
)
I think you need to make the selected value a string. There's also some value in using extension methods as detailed here.

Categories

Resources