DropDownListFor using ViewData - c#

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/

Related

How to create a combobox WITHOUT Windows Forms

I am doing a web application in Visual Studio in C#. The application should be able to write out students and courses which they attend. Anyway, I added a "Create view", where I can create new courses, but now I want to add a COMBOBOX there so that I am able to choose students and for the chosen one enter a new course. Can somebody tell me how to add a combobox WITHOUT using Windows Forms? I need code, and explanation where to insert it! I hope you can help me. Thank you.
You need to use <select> in html,to fill your list and dynamically create you need to fill your list in your controller like this:
List<Student> students = new List<Student>();
Student std = new Student();
....
students.Add(std);
Then return your View and pass it your list:
return View(students);
In your View set your View Model like this:
#model IEnumerable<Student>
Then add a foreach loop and create your comboBox:
<select id="studentList">
foreach(Student s in Model)
{
<option>#s.Name</option>
}
</select>
Or you can use Html.DropDownListForHelper method, and it will create a list automatically for you:
#Html.DropDownListFor(m => m.Name)
I give you a sample,you can change it like whatever you want,you didn't provide enough information...
Since I read that you did the "Create View" action, I assume you're making a web application in the ASP.NET MVC framework. A combobox on the web is merely this:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
-> Each "option" tag represents a choice in the dropdown.
Reference & more info on the "select" tag: http://www.w3schools.com/tags/tag_select.asp
But for full guidance on how to use the MVC framework I'd recommend you'd start a tutorial of some sorts, for example this one: http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started
The solution is not ASP.net specific, rather its part of html. The input control you're looking for is the select element. If you're using MVC, you can use the DropdownListFor extension method.
If you're using other server technologies they may have their own html rendering helpers.

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.

How add DropDownList without binding to ViewData?

I do:
#Html.DropDownList("ddBrand", (IEnumerable<SelectListItem>)ViewBag.Brands, new {onchange = "JavaScript:Act()"})
But when I press submit it needs the field "ddBrand" in View Model.
How can I add DropDownList to View without binding to ViewData? (without adding field "ddBrand" in View Model)
Simply generate the HTML. You can create the options in a for loop. You can give different name to the id and name attributes.
<select id="ddBrand" name="ddBrand">
<option value="value">Text</option>
</select>

Asp.Net MVC Model with related drop downs

I am building a screen in my C# Asp.Net MVC application, which has a few related drop downs.So, for example, I select 'Category', and then a 2nd drop down should display all related sub categories for the selected category.
So, would the model contain a List, used to build the Category drop down, and then a List, initially empty. On the selection of the category, I need to do a post back, passing back the id if the selected Category, then populate the List<> Sub Categories... and then build the Sub Category drop down?
Hopefully someone can assist with the design of my model. The model would also have quite a few non-list related data for the item being edited. And I think the model would also need a 'CategorySelectedId', so that I know what was selected?
The nicest way is to use AJAX for this. You'll have to hook the change event to your first select box, and once it is changed, you'll do a AJAX request with the selected value to some Action. The action will return a JSON list, which will be parsed and put in the next select box.
Update
The model for the JSON returning action can be an anonymous type really, or a IEnumerable of SelectListItem. Use Linq: `mycollection.select(item=> new SelectListItem() { Name = item.Name, Value = item.ID.ToString() });
If we assume the page looks like this:
<form>
<select id="MainCat" name="MainCatID">
<option value="1">First option</option>
<option value="2">First option</option>
<option value="3">First option</option>
</select>
<select id="SubCat" name="SubCatID" disabled="disabled">
<option value=""> -- Please select a main category -- </option>
</select>
</form>
Your model would look like:
public class MyModel {
public int MainCatID {get;set;}
public int SubCatID {get;set;}
public IEnumerable<SelectListItem> MainCats {get;set;}
}
Of course you could add validation attributes etc.

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