DropDownListFor enums in EF5 selected item - asp.net-mvc

Like in DropDownListFor enums in EF5 I would like to generate a dropdown list from a code first EF enum. The solution provided works but it does not set the selected value. How I can do this? I have tried the code below but it does not work (where the last parameter in SelectList re-represents the selected value:
#Html.DropDownListFor(model => model.TypeID, new SelectList(Enum.GetValues(typeof(Models.OrganisationType)),model.TypeID))
I have answered my question. The above code correctly sets the selected value in the dropdown. For some reason MVC did not like my enum and property names when I used the word 'Title' for my property and 'Titles' for my enum as below:
#Html.DropDownListFor(model => model.Title, new SelectList(Enum.GetValues(typeof(BL.Titles)),Model.Title),"")
Also I am using one View for both Create and Edit and therefore had to add code to stop MVC trying to set the selected value before the object has been created:
#if(Model == null) {
#Html.DropDownListFor(model => model.PersonsTitle, new SelectList(Enum.GetValues(typeof(HLRA.eForms.BL.PersonsTitle))),"")
}
else
{
#Html.DropDownListFor(model => model.PersonsTitle, new SelectList(Enum.GetValues(typeof(HLRA.eForms.BL.PersonsTitle)),Model.PersonsTitle),"")
}
Does anyone know a more elegant way?

This:
#Html.DropDownListFor(model => model.PersonsTitle, new SelectList(Enum.GetValues(typeof(HLRA.eForms.BL.PersonsTitle)))))
should be enough.
I don't like your condition:
#if(Model == null)
You should have your Model defined and the property "PersonsTitle" should be set with your default value.

Related

Where does Html.DropDownList return the selected value to?

I am trying to use a dropdownlist in my mvc application, but am very confused by how it operates. It appears that you pass the list that appears in the dropdown, and a temporary description, but never tell it where you would like the selected value stored. Am I missing something or how do I retrieve a value from my drop-down list?
My drop-down list:
#Html.DropDownList("EmployeeNames", null, "Select an Employee", htmlAttributes: new { #class = "form-control" })
My current drop-down list appears correctly but I am unable to retain the selected value.
You tell where the value to be stored, the property EmployeeNames from the current Model.
You can take a look at MVC Model Binding. The first parameter of DropDownList is the name. The MVC bind the value by the form elements name.
The following
#Html.DropDownList("EmployeeNames", null, "Select an Employee", htmlAttributes: new { #class = "form-control" })
In HTML will look similar to this
<select id="EmployeeNames" name="EmployeeNames">
<!-- options -->
</select>
You notice name="EmployeeNames", that will help to bind to the property EmployeeNames from the curent Model.
Actually, it's pretty straightforward.. just grab the variable on the method call which handle the particular form action in your controller, if the name of your DropDownList is EmployeeNames , then your method should look like this
public ActionResult handleForm(string employeeNames)
{
return View();
}

Nullable object must have a value While rendering a CheckBox in Razor

I am trying to create a CheckBox in MVC using Razor and here is the Below code for it :
#Html.CheckBoxFor(m => m.PDModel.EducationMasterList[0].eduMarksheet, new { #class = "marksheet" })
But it is showing error Cannot implicitly convert 'bool?' to 'bool'. Are you missing the type cast.
To Solve this i have used #Html.CheckBoxFor(m => m.PDModel.EducationMasterList[0].eduMarksheet.Value, new { #class = "marksheet" }) and it is giving this error : Nullable object must have a value.
and #Html.CheckBoxFor(m => m.PDModel.EducationMasterList[0].eduMarksheet.GetValueOrDefault(), new { #class = "marksheet" }) and it is giving this error : Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Any Suggestion will be thankful.
Thanks in Adavance
You cannot create a checkbox for a nullable bool. A check box has 2 states, checked/true and unchecked/false, but a nullable bool has 3 states, true, false and null so its not possible to post back a value indicating if its false or null.
You can use
#Html.EditorFor(m => m.PDModel.EducationMasterList[0].eduMarksheet, ...
which will render a dropdown list containing 3 values ("True", "False" and "Not set"). Another option is to create 3 radio buttons.
Note that #Html.CheckBoxFor(m => m.PDModel.EducationMasterList[0].eduMarksheet.Value, ..) would be pointless since it creates a checkbox and associated hidden input with the attribute name="EducationMasterList[0].eduMarksheet.Value" so when it posted back it would not match any model property and binding would fail.

How will model binder deals with Readonly & disabled

I have the following two items , one which is readonly:-
#Html.TextBoxFor(model => model.Technology.Tag, new
{ #readonly = "readonly" })
While the other is Disabled:-
#Html.DropDownListFor(model => model.Customer.NAME, ((IEnumerable<TMS.Models.AccountDefinition>)ViewBag.Customers).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.ORG_NAME),
Value = option.ORG_NAME.ToString(),
Selected = (Model != null) && (Model.Customer != null) & (option.ORG_NAME == Model.Customer.NAME)
}), "Choose...", new { disabled = "disabled" })
so will the asp.net mvc model binder bind the two items? , or it will ignore any read-only and any disabled fields ?
It will bind them, but as long as you have populated them with the correct data, that shouldn't matter. Also, you can have your code that maps these models to the entity, assuming you are using view models, just ignore the values in question. Assuming this is a standard HTTP Post from the form, HTTP will not post disabled or readonly fields, which means they will be null or the default value in the model, so you need to account for that.
If you want the binder to ignore these values, use TextBox and DropDownList and make sure they are not named the same as your properties. If you do not use 'For' you will need to add code in the view to set the values.
ReadOnly text fields get bound.
I've been trying to find a way around the unbound dropdownboxfor values. Here's what I came up with:
$('#xxx').change(function() {$(this).val(lastSel_xxx);});
var lastSel_xxx = $("#xxx option:selected").val();
Use the code above for each HTML element in your view (this will require you to document each ID output) and replace 'xxx' with the element name.
When a user selects another option besides the initial option selected, it reverts back to the original.
HOpe this helps!

Dropdown in ASP.NET MVC 3

I am new to MVC so probably confused . can somebody please explain me the dropdown in razor.my questions are-
What is the difference in dropdownlist and dropdownlistfor
how do i Pass ID column of my database table as value and NAME column as text.
How do i add "other" to the dropdownlist.
how do i access the selectedlistitem in code behind.
if possible please explain with an example.
DropDownList is generated by code like this:
#Html.DropDownList("PersonId", new SelectList(Model.People, "Id", "Text");
On the other hand, DropDownListFor is generated like this:
#Html.DropDownListFor(m => m.PersonId, new SelectList(Model.People, "Id", "Text")
Problem with DropDownList is that it has a magic string and if you decide to refactor the model later on, there's a high change you'll forget to change the magic string too.
You could do a LINQ query like this:
var datalist = New SelectList(from x in _peopleService
select new SelectListItem { Text = x.Name, Value = x.Id});
If you don't have a service or an ORM between it you need to apply it to your situation, but you can generate a list like that.
After nr 2, you can
datalist.Add(new SelectListItem() { Text = "Other", Value = "-1"});
Also you have to put that datalist in your viewmodel/model that is passed to the View, so you can generate a selectlist item with that. In this case you could just do:
#Html.DropDownListFor(x => x.PersonId, Model.PersonList);
if you stored the list as PersonList in Model.
In your Viewmodel (Well, model in mvc) you have a property where the selected item will be stored, look at the 1st question - In this instance the selected item's id will be stored in the PersonId property.

HTML.DropDownList does not respect pre-selected value

I want to use Html.DropDownList(string name, IEnumerable SelectList, Object htmlAttributes) to render a select list with a preselected value for me.
My select list is in the model object of my view, so I have been writting the following code:
<%= Html.DropDownList("aName", mySelectList, new { }) %>
Which will render the select list without the pre-selected value.
A workaround I have found is passing the SelectList as ViewData and doing the following:
In the controller:
ViewData["TimeZones"] = mySelectList;
In the view:
<%= Html.DropDownList("TimeZones", null, new { }) %>
This way the select list will be rendered with the preselected value, however, I don't want to be forced to pass my select list as view data. What am I doing wrong? Thank you in advance for your help.
You can simply do this (it works):
<%: Html.DropDownList("DropdownName", new SelectList(ListItems, "Value", "Text", selectedItem), htmlAttributes)%>
Let me know in case this does not work for you.
Autobinding the selected item
The other approach is to automatically bind the selected item, and passing the list of items as parameter to the DropDownList helper method.
In the controller you do exactly the same thing as before, just don’t set to true the Selected property of any item. Then you also have to put into the view model the value of the item you want to select.
var model = new IndexViewModel()
{
ListItems = items,
SelectedItem = 2
};
And finally in the view, you use the overload which accepts also the selectList parameter:
<%= Html.DropDownList("SelectedItem", Model.ListItems) %>
The only difference in the HTML rendered is that, with first approach, the name of the HTML select element is ListItems, with the second it is SelectedItem.
These approaches are fine if you are creating your own list, but they are not the optimal solution if you are receiving the list of options for an external method, for example from a DB repository.
Take a look at this link
I know this is an old post, but I ran into a similar issue in MVC5. The solution is simple, but I struggled with it for a while, so I thought I'd share.
VS auto-generates DropDownLists with this in the view:
#Html.DropDownList("EpisodeTypeId", null, htmlAttributes: new { #class = "form-control" })
In the controller, VS auto-generates the ViewBag code differently for a Create vs. and Edit.
Here's the code from a create:
ViewBag.EpisodeTypeId = new SelectList(db.EpisodeTypes, "Id", "Name");
And from an edit:
ViewBag.EpisodeTypeId = new SelectList(db.EpisodeTypes, "Id", "Name", episode.EpisodeTypeId);
That fourth argument is important for Edits, as you might expect. If you leave it out, the database value for that record will not be pre-selected in the DropDown.
The VS auto-generated code will be correct, but if you're adding in fields manually later, this is easy to miss.

Resources