MVC Dropdown List isn't binding to the model - c#

I am trying set up a simple dropdown list but I dont seem to be able to get it to bind to the Model.
I am using Asp.Net MVC and nhibernate.
My dropdown list is declared like so:
<%= Html.DropDownListFor(model => model.Project, (IEnumerable<SelectListItem>)ViewData["Projects"], " -- Select -- ", new { name = "Project" })%>
I set up the select list like so:
ViewData["Projects"] = new SelectList(projectRepository.GetAll(), "EntityGUID", "Name", editEntity.Project);
This seems to bind the select list to the Dropdown fine, but the SelectedValue is not set.
it shows up as the default --- Select ---
Also when I save this data, the dropdown does not bind to the model, I have to manually set the object like so to save it:
entity.Project = projectRepository.GetById(new Guid(Request["Project"].ToString()));
I believe I have take the correct messures to have this item bind directly to my model.
Is there something I am missing here?
Many thanks for your time,
Rod

OMG I found the problem........
It has taken me 3 days to turn:
<%= Html.DropDownListFor(model => model.Aspect, (IEnumerable<SelectListItem>)ViewData["AspectTypes"])%>
into:
<%= Html.DropDownListFor(model => model.Aspect.EntityGUID, (IEnumerable<SelectListItem>)ViewData["AspectTypes"])%>
model.Aspect**.EntityGUID**
I had to bind the drop down to the objects guid, not the object itself.
Doh....Im feeling the pain, much work to catch up on.
Thanks for your time.

This is just a hunch since your code looks good to me but I don't think you need to include the forth parameter when defining your SelectList. Setting that field might be distrupting the normal flow of things (overriding your model binding) and I have never bound a DropDownList and had the SelectList's SelectedValue set.
Try removing that and see how it goes.
SelectList(projectRepository.GetAll(), "EntityGUID", "Name");
Also I asked a question a while back regarding how to implement DropDownList in MVC2 that you might find useful.

Related

How do I get the text value from a <select> in ASP.NET MVC

I am using ASP.NET Core. I currently use the following <select> element in my view, within a form:
<select asp-for="CarTypeId"></select>
When I make the post I will only get the value for Model.CarTypeId.
However I have another field, Model.CarType which I want to give the value of the selected text in the <select>.
You can add another model property for this and set it during select event using jquery or use formcollection.
It is not a good practice, only the type id should be enough, and use it as a reference to the car type itself, shouldn't be one more field as you described, as this will be redundant.
Anyway the solution is adding a hidden field for CarType, and upon cartypeid change, update its value.
something like this
$('#CarTypeId').on('change', function(){
// this will get the text of the selected option
var theText = $('#CarTypeId').find(":selected").text();
//Update value of the hidden field
$('#CarType').val(theText);
});

DropDownListFor problems

I was wondering if anyone has ever experienced a problem like I'm currently having.
Controller:
_OpsAdminViewModel.userRoleID = _OpsAdminViewModel.retrieveHighestUserRoleGuidFromUserID(id.Value);
_OpsAdminViewModel.ActiveRoleList = _OpsAdminViewModel.GetActiveRoles();
_OpsAdminViewModel.UserRoleSelectList = new SelectList(_OpsAdminViewModel.ActiveRoleList, "RoleID", "RoleName", _OpsAdminViewModel.userRoleID);
View:
#Html.DropDownListFor(model=>model.selectedRoleID, Model.UserRoleSelectList)
Now, here is where it gets very odd. When I place a break on the Controller's Return line or the View's DropDownListFor line, I literally see that the value I want to have selected should be selected. Expanding the UserRoleSelectList object, reveals the correct "SelectedValue" ID and in the "Results View", the correct value has a "True" for selected. However, when the page is rendered, the pull-down menu is displaying the 0-position element of the pull-down menu.
Model binding works by binding to the value of your property. When your use DropDownListFor() the method internally builds a new IEnumerable<SelectListItem> and sets the Selected property based on the value of your property. In your case, the value of selectedRoleID does not match the value of one of the options so the first option is selected (because something has to be).
Set the value of selectedRoleID in the GET method before you pass the model to the view
model.selectedRoleID = _OpsAdminViewModel.userRoleID;
return View(model);
and delete the last parameter in your SelectList constructor since its pointless.

Dropdownlist in asp.net mvc technical working reference

I have invested my few hours figuring out how to work with dropdownlists..
finally I have a working piece of code.. but I do not know how it works.
http://www.youtube.com/watch?v=79aYSOcmpV8&list=PL6n9fhu94yhVm6S8I2xd6nYz2ZORd7X2v
In Controller.
ViewBag.Breed = new SelectList(db.Breeds, "breed", "breed");
In view
#Html.DropDownList("Breed", "Select Breed")
How does it works??
ViewBag.Breed = new SelectList(db.Breeds, "breed", "breed");
The first parameter here is the data source of your dropdown list.
For the second parameter, you can pass it a property of your model, then it would become the value of your drop down.
The third parameter is the display text of your drop down list.
#Html.DropDownList("Breed", "Select Breed")
The first parameter is the name of your SelectList ViewBag. The second one is the default text for your dropdown list when nothing is selected yet.

DropDownListFor using ViewData

Im trying to change the code in an existing project to make a DropDownListFor to select an item. I have read countless of threads but i do not get an specific item to get selected;
This is what i got;
Controller;
ViewData("MyDropDownList") = new SelectList(_myRepository.GetData, "data_id", "name"})
View;
#Html.DropDownListFor(Function(m) m.data_id, TryCast(ViewData("MyDropDownList"), SelectList))
And this produces a nice list that looks something like this;
<select id="someId" name="someName" data-val="true">
<option value="aec385a7-bd77-4b94-9fbb-130487e3e62e">Option1</option>
<option value="5edee514-e6ca-456f-a8fa-71bde67351a1">Option2</option>
<option value="8a293328-8b11-47b7-bc9a-ceddf2e6a355">Option3</option>
</select>
After abit of reading i was pretty sure that this would work for making "Option2" selected;
ViewData("MyDropDownList") = new SelectList(_myRepository.GetData, "data_id", "name", "5edee514-e6ca-456f-a8fa-71bde67351a1"})
But it didn't, i have also tried this;
ViewData("MyDropDownList") = new SelectList(_myRepository.GetData, "data_id", "name", New With {Key .id = "5edee514-e6ca-456f-a8fa-71bde67351a1"} })
What am i doing wrong? VB is not my cup of tea so it might as well just be a syntax screw up. Any input is appreciated.
In MVC if the view is strongly typed the selectlist’s selected option will be overridden and the selected option property set on the constructor will never reach the view and the first option in the dropdown will be selected instead (why is still a bit of a mystery). To overcome this issue all that needs to be done is to rename the DropDownList in the view and also the name of the ViewData’s key in the controller to something other than the name set in the model , and the selected option will then reach the view. Unfortunately when posting the form you will have to access the selected option’s value from the FormCollection rather than a strongly typed object which is a little annoying.
Source :http://www.dotnetguy.co.uk/post/2009/06/25/net-mvc-selectlists-selected-value-does-not-get-set-in-the-view/

Templating Html.EditorFor for specific datatype in ASP.Net MVC3?

I am working on a .Net MVC3 application. I have a couple different models which all have an attribute or two with a DataType of varchar(1). For each of these want to have a drop down menu for Yes/No with a value of 'Y' or 'N'.
My current solution is as follows: I have a method in a public class which sends gives me my List of Yes/No values for the dropdown:
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem() { Text = "Yes", Value = "Y" });
items.Add(new SelectListItem() { Text = "No", Value = "N" });
return items;
In my Controller, I then set this list into the ViewBag and send it into the View:
ViewBag.YesNo = new SelectList(repository.GetYesNo(), "Value", "Text");
And then I use it for a specific Model attribute like this:
#Html.DropDownListFor(model => model.PARAMETER_REQUIRED, (SelectList)ViewBag.YesNo)
This gets the job done but I don't like the ViewBag method because it's pretty tedious to maintain it when switching Views and I don't like having to repeat code. I want to change this up so that I can just use
#Html.EditorFor(model => model.PARAMETER_REQUIRED)
and have Razor know that I want this to be a DropDown with my Yes/No attributes.I also want to have this be reusable so that I can use the same template for any fields (in other models) that I want to edit with this Yes/No dropdown.
Is this possible? I know that 'templating' DisplayFor is possible. Can we achieve something similar with EditorFor?
Here are some really good examples of the built-in display templates and editor templates. Take a look at EditorTemplates/Boolean.ascx. You'll want something like this, in fact I'm not sure why you can't use the Boolean template as-is and change your view model to just be List or other suitable collection. Then, if necessary, you can customize the Boolean editor template to give you the exact DropDownList view you need.
An edit template uses the view assigned to it by the type given; what you may want to do is create a named template and apply the name to the Html.EditorFor overload. Then, you can create a specialized template for that scenario, and not have it be globally defined for the char type. Check out this example.

Categories