DropDownListFor problems - c#

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.

Related

How to set null value (by default) to drop-down list in MVC 4

In my model class for view, I have an enum type property SubjectType:
[Required(ErrorMessage = "This field is required.")]
public SubjectType SubjectType { get; set; }
I would like to create drop-down list for this property. But by default I would like it to be set to null so that user has to choose something, and the validation message will be shown if he would try to submit form without choosing any option.
What is the best approach to achieve this?
I was trying to change SubjectType property to nullable, and setting the default value to null, but the validation still passed on this field (somehow) and the form was submitted to the server. By default the value of this field was set to the first value from enum definition. No JavaScript allowed, I'd like to keep everything in code-behind. I will be grateful for any advice.
so far i render it this way:
#Html.DropDownList("SubjectType", EnumHelper.GetSelectList(typeof(SubjectType)))
#Html.LabelFor(model => model.SubjectType)
#Html.ValidationMessageFor(model => model.SubjectType)
You are able to solve problem doing this:
Change submit button to button with onclick action, then validate it in javascript and if form and this enum field is valid submit the form using jQuery.
Edit: I think the problem was three fold. first your attribute is named SubjectType but your dropdown is named Type so it cannot be bound to SubjectType.
second, Apparently you have to use #HTML.dropdownlistfor(). I did a viewsource with my two different versions dropdown and dropdownlistfor and dropdownlistfor is the only one that adds the validation classes (see below)
third, we needed to add the option label parameter "Select a Type" as a default value. I'm sure it'll work for you now.
In Model:
[Required(ErrorMessage = "Error!")]
public string SubjectType{ get; set; }
In Html:
#Html.DropDownListFor(m => m.SubjectType, new SelectList(Enum.GetNames(typeof(SubjectType))), "Select a Type", new { #class = "pretty" } )
now I see you have a helper that furnishes an enumerable I think that will be just fine if you replace my second param with that.
Dropdownlist vs DropdownlistFor Rendering of Select Element:
DropdownList:
<select name="SubjectType" class="pretty" id="SubjectType">...</select>
DropdownListFor:
<select name="SubjectType" class="pretty" id="SubjectType" data-val-required="Error!" data-val="true">...</select>
As you can see data-val-required and data-val classes are missing when doing a simple dropdown thus not turning on validation FOR that attribute. Sorry for all the pain of getting here. Don't forget to mark me right if it works.

when select value from dropdwonlist i want to show it in for example div

I have a dropdownlist inside a form and a div. I want that, when i select a value from the dropdownlist, it shows in the div.
I've succeeded in this, but the problem is that the following selections ,after first one, are deleting previous results from the div.
public ActionResult SelectStudWhoWantReport(int StudentId = 0)
{
IEnumerable<SelectListItem> items = db.Students.Select(c => new SelectListItem
{
Value = SqlFunctions.StringConvert((double)c.StudentID).Trim(),
Text = c.StudentName
});
ViewBag.StudentId = items;
Student WhomakeReport = db.Students.Find(StudentId);
ViewBag.Name = WhomakeReport.StudentName;
return View();
}
viewbag is the value that apear in div, When I select that how can I append the value of the second select with the first select to show the two in the div.
I think you are using a bad approach to solve your problem.
You are getting the result of the selection on your controller class, through a form submission I supose, and later send it to your View.
The problem is that when you call the controller your page is reloaded, thus you loose the previous info. There are different ways in which you'd be able to store previous results and build them on the View.
However, I think it's better that I explain you a more correct approach to solve this problem.
You should have a dropdownlist component on your View, which you load through your controller. I supose you already have this.
When the selection is made, instead of submitting the form, make an AJAX call to a method in the server which makes what you're currently doing in your controller (get the result depending on the selected id) and, instead of returning an ActionResult, just return the value you want.
When the AJAX callback returns, you'll have the result on your client code, so you just have to append it after previous results.
This approach not only is better from a MVC pattern point of view, it's also easier to implement and will allow your users to select elements in the dropdownlist and see the results without having to reload the whole page.

setting default item on dropdownlistfor

I have populated a selectlist in my viewmodel in the form:
DeliveryCentres = new SelectList(deliveryCentres, "Id", "CentreName");
in my View I have:
#Html.DropDownListFor(m => m.DeliveryCentreId, Model.DeliveryCentres, "-- Not Required --");
The problem is that on display the dropdown defaults to the first item in the list as opposed to the -- Not Required -- value.
How do I make this the default?
#Stephen Muecke has answered the question. I just needed to leave the ID as null in the ViewModel before rendering.
From comments:
The selected value will be whatever the value of DeliveryCentreId is. If its value is null or does not match one of the option values, then the "Not Required" option will be selected

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.

MVC Dropdown List isn't binding to the model

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.

Categories