Dropdownlistfor returns null value - asp.net-mvc

I have a customer class with a property Gender. I created a list of Gender type which contains and id number and Gender type. When form is submitted, I am getting null value.
View
#model MovieRentals.ViewModel.CustomerView
<div class="form-group">
<h4>#Html.LabelFor(l => l.Customer.BirthDate)</h4>
#Html.DropDownListFor(l => l.CustomerGender, new SelectList(Model.CustomerGender, "GenderId", "GenderType"), "Select Gender", new { #class = "form-control" })
</div>
Model
public class CustomerView
{
public IEnumerable<MembershipType> MembershipTypes{ get; set; }
public Customer Customer { get; set; }
public List<GenderClass> CustomerGender{ get; set; }
}
public class GenderClass
{
public int GenderId { get; set; }
public string GenderType { get; set; }
}
Controller
public ActionResult New()
{
var MembershipTy = _context.MemebershipType.ToList();
var ViewModel = new CustomerView();
ViewModel.CustomerGender = new List<GenderClass>()
{
new GenderClass(){ GenderId = 1, GenderType = "Male"},
new GenderClass() { GenderId = 2, GenderType = "Female"}
};
ViewModel.MembershipTypes = MembershipTy;
return View(ViewModel);
}

You need two properties: one to hold the selected value and one to hold the options. The one that holds the options should be IEnumerable<SelectListItem>. Your GenderClass class is completely superfluous.
Also, using an integer id as the value doesn't make sense when the meaning of that value is not obvious. Here, the fact that 1 means Male only exists in the New action. Anywhere else, you will then have to repeat this logic (which introduces opportunities for errors, e.g. was male 1 or 0). Further, if you decide to change those values, you must remember to change them everywhere. If you want to use an integer id, then you should abstract away the meaning somewhere, be it an enum, static class, database table, etc. The far better choice is to just keep it a string, and use the dropdown merely to enforce normalization of that string value.
public string CustomerGender { get; set; }
public IEnumerable<SelectListItem> CustomerGenderChoices
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Value = "Male", Text = "Male" },
new SelectListItem { Value = "Female", Text = "Female" }
}
}
}
Then, in your view:
#Html.DropDownListFor(m => m.CustomerGender, Model.CustomerGenderChoices, "Select Gender", new { #class = "form-control" })
Alternatively, if you were to use an enum:
public enum Genders
{
Male = 1,
Female = 2
}
Then, in your view model, you would only need one property, just to store the value:
public Genders CustomerGender { get; set; }
Then, in your view, you can make use of EnumDropDownListFor:
#Html.EnumDropDownListFor(m => m.CustomerGender, "Select Gender", new { #class = "form-control" })
As an enum, the value stored would be an int, but the benefit here is that you have a strongly-typed association between those integer values and what they mean. For example, rather than doing something like:
if (customer.CustomerGender == 1) // Male
You can do:
if (customer.CustomerGender == Genders.Male)
Obviously, the second version is much more obvious in meaning.

Related

dropdownlistfor not displaying correct value

My query is getting all the correct values and the selectlist is populated, but my dropdownlist only shows the first value in the selectlist. how can i get it to show the returned value of Captain?
Viewmodel:
public class EditTeamsView : BaseCommunityView
{
...
public IList<Domain.Team> ExistingTeams { get; set; }
...
public EditTeamsView()
{
ExistingTeams = new List<Domain.Team>();
}
}
public class Team
{
...
public string Captain { get; set; }
public IEnumerable<SelectListItem> MemberSelectList { get; set; }
}
View:
#for (var c = 0; c < Model.ExistingTeams.Count; c++)
{
#Html.DropDownListFor(x => x.ExistingTeams[c].Captain, Model.ExistingTeams[c].MemberSelectList,
new { #class = "form-control "})
}
Each option in the dropdown will need a value property and a display property so you may need to change up your Team class's MemberSelectList object to IEnumerable that contains value and text properties.
To set the default value of a drop down list based on a string value like what you have, new up a SelectList that requires an IEnumerable list of objects like what you have, a value property, a text property, and then the default value object.
See here: https://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist.selectlist(v=vs.118).aspx#M:System.Web.Mvc.SelectList.
#Html.DropDownListFor(x => x.ExistingTeams[c].Captain,
new SelectList(Model.MemberSelectList, "Value", "Text", Model.Captain)
)

Formatting a Drop Down List in ASP.NET MVC

I'm building an app with ASP.NET MVC 4. I'm binding my model to a view. In my view, I need a drop down list. That drop down list needs to show quarters. The quarters should be displayed as "Q1", "Q2", "Q3", and "Q4". My model, only has quarter numbers. They are defined like this:
public List<short> Quarters = new List<short>() { get; set; }
public short? SelectedQuarter = null;
public void Initialize() {
Quarters.Add(1);
Quarters.Add(2);
Quarters.Add(3);
Quarters.Add(4);
}
Somehow, I need to prepend "Q" to each value. However, I'm not sure how to do this in ASP.NET MVC. How does someone do this?
Thanks!
Create a SelectList to be used by DropdownListFor() so that you bind the selected option to property SelectedQuarter, but display the 'friendly' name.
View model
public class MyViewModel
{
[Display(Name = "Quarter")]
[Required]
public short? SelectedQuarter { get; set; } // must be a property, not a field!
IEnumerable<SelectListItem> QuarterList { get; set; }
}
Controller
public ActionResult Edit()
{
MyViewModel model = new MyViewModel();
ConfigureViewModel(model);
return View(model);
}
public ActionResult Edit(MyViewModel model)
{
if(!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// model.SelectedQuarter contains the selected value
}
private void ConfigureViewModel(model)
{
model.SelectedQuarter = new List<SelectListItem>()
{
new SelectListItem() { Value = "1", Text = "Q1" },
new SelectListItem() { Value = "2", Text = "Q2" },
new SelectListItem() { Value = "3", Text = "Q3" },
new SelectListItem() { Value = "4", Text = "Q4" },
}
}
View
#model MyViewModel
#using(Html.BeginForm())
{
#Html.LabelFor(m => m.SelectedQuarter)
#Html.DropDownListFor(m => m.SelectedQuarter, Model.QuarterList, "-Please select-")
#Html.ValidationMessageFor(m => m.SelectedQuarter)
<input type="submit" />
}
Assuming you have this property:
public List<short> Quarters { get; set; }
Then in your view or any other consuming code you can generate a list of strings with something like:
model.Quarters.Select(q => "Q" + q)
or:
model.Quarters.Select(q => string.Format("Q{0}", q))
However, semantically it really feels like this belongs on a view model and not in consuming code. Ideally the view should only ever need to bind directly to properties on the view model, not transform those properties. Something like this:
public IEnumerable<string> QuartersDisplay
{
get { return Quarters.Select(q => string.Format("Q{0}", q)); }
}
Then consuming code can just bind to that property:
model.QuartersDisplay
(If the model is a domain model then I'd recommend introducing a view model between the domain and the view, since this wouldn't belong on a domain model.)
Thinking about this a little more... Do you want one property with both the displays and the backing values for the drop down list? That would likely be a IDictionary<short, string>, I imagine? Something like this:
public IDictionary<short, string> QuartersOptions
{
get { return Quarters.ToDictionary(q => q, q => string.Format("Q{0}", q)); }
}
In which case you'd bind to that property:
model.QuartersOptions
Keep in mind that a drop down list often binds to two things. The property which holds the list of possible values (which is what we've built here) and the property which holds the selected value (which remains your SelectedQuarter property).

Most efficient way to render data into a form from a populated model

I've got a populated entity filled with checkbox selector, few strings. that has to be built linearly(for each row) in a loop in a div structure.
The entity:
public class Hours
{
[Key]
public int SliceID { get; set; }
public string SliceName { get; set; }
public string Slice { get; set; }
public string StartTime { get; set; }
public string EndTime { get; set; }
public bool Selected { get; set; } //if slice is checked by user on search screen
}
The action which will gather all time slices for display:
public ActionResult Search_Times()
{
int iInstId = 1;
Test.Models.DataLayer db = new Test.Models.DataLayer();
Test.Models.TestDB context = new Models.TestDB();
IEnumerable<Test.Models.Hours> lst = db.GetSlices(context, iInstId).OrderBy(a => a.SliceID);
// ViewBag.SliceList = lst;
return View(lst);
}
I want to render those fields in a specific part of my body page along with some class/div formatting along the way.
For example, If I use EditorForModel :
in Main page:
#model IEnumerable<Test.Models.Hours>
#Html.EditorForModel()
in the Hours EditorTemplate:
#model Test.Models.Hours
<div>
#Html.CheckBoxFor(
x => x.Selected,
new {
#class = "jcf-unselectable",
id = HtmlHelper.GenerateIdFromName("cb_slice." + ViewData.TemplateInfo.GetFullHtmlFieldName(""))
}
)
// this should be a label too, made for example to show text from data.
#Html.DisplayTextFor(x => x.SliceName)
#Html.LabelFor(
x=> x.StartTime,
new {
#class = "info"
})
#Html.LabelFor(
x => x.EndTime,
new {
#class = "info"
})
</div>
The #Html.LabelFor in my case will only show the row's title and not the data (for="" in the source view after rendering), Unlike DisplayTextFor which will show the data but is only a generic text.
I need a way or to fix this current way, To manipulate the data from the model accordingly, Labels will show the data behind their field and I could generate the class,id needed(based on css/html required) inside that label in a loop.
What's the best way to do so, viewbags/templates/etc?

MVC DropDownList SelectedValue not displaying correctly

I tried searching and didn't find anything that fixed my problem. I have a DropDownList on a Razor view that will not show the the item that I have marked as Selected in the SelectList. Here is the controller code that populates the list:
var statuses = new SelectList(db.OrderStatuses, "ID", "Name", order.Status.ID.ToString());
ViewBag.Statuses = statuses;
return View(vm);
Here is the View code:
<div class="display-label">
Order Status</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)
#Html.ValidationMessageFor(model => model.StatusID)
</div>
I walk through it and even in the view it has the correct SelectedValue however the DDL always shows the first item in the list regardless of the selected value. Can anyone point out what I am doing wrong to get the DDL to default to the SelectValue?
The last argument of the SelectList constructor (in which you hope to be able to pass the selected value id) is ignored because the DropDownListFor helper uses the lambda expression you passed as first argument and uses the value of the specific property.
So here's the ugly way to do that:
Model:
public class MyModel
{
public int StatusID { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
ViewBag.Statuses = statuses;
var model = new MyModel();
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}
View:
#model MyModel
...
#Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)
and here's the correct way, using real view model:
Model
public class MyModel
{
public int StatusID { get; set; }
public IEnumerable<SelectListItem> Statuses { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
var model = new MyModel();
model.Statuses = statuses;
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}
View:
#model MyModel
...
#Html.DropDownListFor(model => model.StatusID, Model.Statuses)
Make Sure that your return Selection Value is a String and not and int when you declare it in your model.
Example:
public class MyModel
{
public string StatusID { get; set; }
}
Create a view model for each view. Doing it this way you will only include what is needed on the screen. As I don't know where you are using this code, let us assume that you have a Create view to add a new order.
Create a new view model for your Create view:
public class OrderCreateViewModel
{
// Include other properties if needed, these are just for demo purposes
// This is the unique identifier of your order status,
// i.e. foreign key in your order table
public int OrderStatusId { get; set; }
// This is a list of all your order statuses populated from your order status table
public IEnumerable<OrderStatus> OrderStatuses { get; set; }
}
Order status class:
public class OrderStatus
{
public int Id { get; set; }
public string Name { get; set; }
}
In your Create view you would have the following:
#model MyProject.ViewModels.OrderCreateViewModel
#using (Html.BeginForm())
{
<table>
<tr>
<td><b>Order Status:</b></td>
<td>
#Html.DropDownListFor(x => x.OrderStatusId,
new SelectList(Model.OrderStatuses, "Id", "Name", Model.OrderStatusId),
"-- Select --"
)
#Html.ValidationMessageFor(x => x.OrderStatusId)
</td>
</tr>
</table>
<!-- Add other HTML controls if required and your submit button -->
}
Your Create action methods:
public ActionResult Create()
{
OrderCreateViewModel viewModel = new OrderCreateViewModel
{
// Here you do database call to populate your dropdown
OrderStatuses = orderStatusService.GetAllOrderStatuses()
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(OrderCreateViewModel viewModel)
{
// Check that viewModel is not null
if (!ModelState.IsValid)
{
viewModel.OrderStatuses = orderStatusService.GetAllOrderStatuses();
return View(viewModel);
}
// Mapping
// Insert order into database
// Return the view where you need to be
}
This will persist your selections when you click the submit button and is redirected back to the create view for error handling.
I hope this helps.
For me, the issue was caused by big css padding numbers ( top & bottom padding inside the dropdown field). Basically, the item was being shown but not visible because it was way down. I FIXED it by making my padding numbers smaller.
I leave this in case it helps someone else. I had a very similar problem and none of the answers helped.
I had a property in my ViewData with the same name as the selector for the lambda expression, basically as if you would've had ViewData["StatusId"] set to something.
After I changed the name of the anonymous property in the ViewData the DropDownList helper worked as expected.
Weird though.
My solution was this...
Where the current selected item is the ProjectManagerID.
View:
#Html.DropDownList("ProjectManagerID", Model.DropDownListProjectManager, new { #class = "form-control" })
Model:
public class ClsDropDownCollection
{
public List<SelectListItem> DropDownListProjectManager { get; set; }
public Guid ProjectManagerID { get; set; }
}
Generate dropdown:
public List<SelectListItem> ProjectManagerDropdown()
{
List<SelectListItem> dropDown = new List<SelectListItem>();
SelectListItem listItem = new SelectListItem();
List<ClsProjectManager> tempList = bc.GetAllProductManagers();
foreach (ClsProjectManager item in tempList)
{
listItem = new SelectListItem();
listItem.Text = item.ProjectManagerName;
listItem.Value = item.ProjectManagerID.ToString();
dropDown.Add(listItem);
}
return dropDown;
}
Please find sample code below.
public class Temp
{
public int id { get; set; }
public string valueString { get; set; }
}
Controller
public ActionResult Index()
{
// Assuming here that you have written a method which will return the list of Temp objects.
List<Temp> temps = GetList();
var tempData = new SelectList(temps, "id", "valueString",3);
ViewBag.Statuses = tempData;
return View();
}
View
#Html.DropDownListFor(model => model.id, (SelectList)ViewBag.Statuses)
#Html.ValidationMessageFor(model => model.id)

DropDownListFor selection not working -- again

Yeah, I know, this question's been asked/answered 34798796873.5 times. I looked through all 3 bajillion of them, and I still have the problem. What am I missing here?
I tried several approaches and none of them work. Here are my latest attempts:
<%:Html.DropDownList("Author",
Model.AuthorItems.Select(i =>
new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString(),
Selected = i.Id == Model.Author.Id
}), "無し")%>
<%:Html.DropDownListFor(m => m.Author,
new SelectList(Model.AuthorItems,
"Id",
"Name",
Model.Author),
"無し") %>
My view model is very straightforward:
public class EditArticleViewModel
{
public AuthorItem Author { get; set; }
public IList<AuthorItem> AuthorItems { get; set; }
public class AuthorItem
{
public int Id { get; set; }
public string Name { get; set; }
}
}
I made sure my action is working correctly; sure enough, Author has an Id of 5, and AuthorItems has an entry whose Id is 5.
I even tried overriding Equals and GetHashCode in the model.
Blahhhhh!!1
In your view model replace:
public AuthorItem Author { get; set; }
with
public int? SelectedAuthorId { get; set; }
and in your view bind the dropdown list to this SelectedAuthorId:
<%:Html.DropDownListFor(
m => m.SelectedAuthorId,
new SelectList(Model.AuthorItems, "Id", "Name"),
"無し"
) %>
Now as long as you provide a valid SelectedAuthorId value in your controller action:
model.SelectedAuthorId = 123;
The HTML helper that renders the dropdown will correctly preselect the item from the list that has this given id.
The reason for this is that in a dropdown list you can select only a single value (a scalar type) and not an entire Author (all that is sent in the HTTP request when you submit the form is this selected value).
DropDownList/DropDownListFor used ModelState value. So set ViewDataDictionary selectedValue in controller.
public ActionResult Index()
{
var model = new EditArticleViewModel
{
Author = new EditArticleViewModel.AuthorItem() {Id = 3, Name = "CCC"},
AuthorItems = new List<EditArticleViewModel.AuthorItem>()
{
new EditArticleViewModel.AuthorItem() {Id = 1, Name = "AAA"},
new EditArticleViewModel.AuthorItem() {Id = 2, Name = "BBB"},
new EditArticleViewModel.AuthorItem() {Id = 3, Name = "CCC"},
new EditArticleViewModel.AuthorItem() {Id = 4, Name = "DDD"},
}
};
ViewData["Author"] = model.Author.Id;
return View(model);
}
View code simple.
<%:Html.DropDownList("Author",
new SelectList(Model.AuthorItems,
"Id",
"Name"), "無し")%>
<%:Html.DropDownListFor(m => m.Author,
new SelectList(Model.AuthorItems,
"Id",
"Name"),
"無し")%>
ViewData key "Author" is using model state binding for selected value.
Hope this help.

Resources