MVC how to change dropdownlist item names - c#

Been googling for a while, but I can't seem to get any closer.
I'm using MVC with an EF Database structure.
I want the dropdownlist items in the View to show up with different names than what they come up with.
Right now, the lambda query returns a list().
I want each item to get a string name depending on their current name. Eventually, the selected field needs to be used in another lambda as the Byte that it was.
Edit
//view
<p>
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>
#Html.DropDownList("vbType", (SelectList)ViewBag.Type, "" , new { onchange = "form.submit();" })
....
//controller
var typeLst = new List<byte>();
var typeQry = from t in db.model1
orderby t.TYPE
select t.TYPE;
typeLst.AddRange(typeQry.Distinct());
ViewBag.vbType = new SelectList(typeLst);
....
Thanks in advance.

You can create a SelectListItem to display in your dropdownlist.
Example:
#Html.DropDownListFor(model => model.YearStartedToPay,
Enumerable.Range(DateTime.Today.Year - 60, 61).OrderByDescending(x => int.Parse(x.ToString())).Select(n => new SelectListItem() { Text = n.ToString(), Value = n.ToString(), Selected = false }).ToList<SelectListItem>(),....)
In this case, I'm creating an Enumerable, that will be your list returned from EF, ordering and selecting as a SelectListItem.

You need to make use of dropdownlist's Value property. Make your list a type of SelectListItem.
Assign Text= [Your Required Text] and Value = [Current Name]

Related

How do I make a select list from a Viewbag item list?

I have a list created from a controller which is passed to a viewbag item:
List<SelectListItem> PTL = new List<SelectListItem>();
List<PT> PTL2 = db.PT.ToList();
foreach (var item in PTL2)
{
PTL.Add(new SelectListItem { Value = item.ID.ToString(), Text = item.Name });
}
ViewBag.PTL2 = PTL2;
Then, in the view, I tried the following from another question here:
#Html.DropDownList("test", new SelectListItem[]{
new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}}
, htmlAttributes: new { #class = "form-control" })
which worked fine, but, if I try to edit it to the following:
#Html.DropDownList("test", ViewBag.PTL2, htmlAttributes: new { #class = "form-control" })
I get various errors.
I have spent hours on this trying different combinations, different castings and more, but, I just don't seem to be making progress.
I have seen so many different errors - the most common one being '
There is no ViewData item of type IEnumerable<SelectListItem> that
has the key “test”'
However, I tried casting and changing the name as per different questions here, but, I just can't seem to get past this.
At this point, I am thinking of just making a manual HTML Drop Down list and a foreach loop for the content, but, this seems a waste.
Does anyone know what I have done wrong?
The second parameter must be a collection of System.Web.Mvc.SelectListItem objects that are used to populate the drop-down list. But, you are using ViewBag property in this case and the type of this is dynamic. So, you must cast it to the collection of the SelectListItem. Otherwise, you will get this error in MVC 4+:
Extension methods cannot be dynamically dispatched
So. as a result just change
ViewBag.PTL2
to
ViewBag.PTL2 as IEnumerable<SelectListItem>.
i hope it is not too late ,this is how i do it with .net core
in your controller ,use below code
public ActionResult ShowCalendar()
{
var programs = new Microsoft.AspNetCore.Mvc.Rendering.SelectList((new Programs().GetAll().ToList(), "ID", "Name")
ViewBag.AllItems = programs;
return View();
}
and in your cshtml file use the below
<select id="ItemID" class="form-control"
asp-items="ViewBag.AllItems">
<option disabled selected>--- #Localizer["PleaseSelect"] ---</option>
</select>
will do the job for you

new SelectList combining to fields but getting only one

Im kinda stuck, I have a drop down that I am trying to combine two fields from the same table into. Its kinda working, here is what I get:
The offending drop down list
As you can see, im pulling stuff I dont want into it, and im not pulling in my last name.
Here is my edit controller:
var DocList =
db.Doctors
.Select(s => new
{
Value = s.ID,
FirstN = s.FirstName,
SurN = s.Surname,
})
;
ViewBag.Doctor = new SelectList(DocList, "FirstN", "SurN", episode.Doctor.ID);
and here is my razor snippet:
#Html.DropDownList("docTest")
What do you guys think is going wrong here? Thanks in advance! :)
Looks like you may be needing to do something like this (it will give the dropdown the id of "docTest"):
#Html.DropDownList("docTest", (SelectList)ViewBag.DoctorOLD, "Place Holder Text", new { #class = "someClass" })
but you may need different functionality, I cannot tell from the amount of code supplied.You may also look into using #html.DropDownListFor if you need to bind the drop down value to a model property.
This SO post here does a great job of explaining html helper drop down list.
You are not binding the value to drop down list.Use below code to get the values
#Html.DropDownList("docTest",(IEnumerable<SelectListItem>)ViewBag.DoctorOLD)
Okay here is the solution im still pretty green at this so where I came unstuck was knowing the overloads. Let me try to explain (and correct me if im wrong)
Okay so we invoke our list. Now our first overload is the ieneumerable, this gets our bunch of stuff we want in our list. Next we want our value field, which is the column in your table that other tables use to link to it, in most cases its the ID column.
Next is the string. In my case its "FullName" and is basically made up of the FirstName and Surname from within my Doctors table.
Anyway if your dyslexic like me just look at the code below and pick it apart :)
The Controller:
ViewData["docFullDetails"] =
new SelectList((from s in db.Doctors
select new
{
FullName = (s.FirstName + s.Surname),
ID = s.ID
}),
"ID",
"FullName");
The View:
<div class="form-control">
#Html.DropDownList("docFullDetails")
#Html.ValidationMessageFor(model => model.Doctor)
</div>
In your controller you should populate your dropdown list like
ViewBag.Doctors = new SelectList(db.Doctors.Select(d => new { d.Id, FullName = d.FirstName + " " + d.LastName }),
"Id", "FullName");
And then in view create dropdown with razor
#Html.DropDownList("DoctorId", ViewBag.Doctors as SelectList, "Select doctor...", new { #class = "form-control" })
Your model for form that you are creating probably should have DoctorId property which you are binding from dropdown
#Html.DropDownListFor(m => m.DoctorId, ViewBag.Doctors as SelectList, "Select doctor...", new { #class = "form-control" })

ASP.NET dropdownlist selected item value gives same ID

I am trying to develop a web application which I Need to save firm name username and password.
When I try to add firm username and password it gives me same firm ID in the database as;
Firmname : YAHOO INC
UserName : asd
Password : pass
İn formload all firms come but when ı try to save firmname, username and pass it gives me same firmname for all user save.
Any advice how I can resolve such issue?
Here is a simple example of how to create a drop down list in ASP.NET MVC using Html.DropDownListFor.
You can do it like this all inlined in your *.cshtml file like so:
#Html.DropDownListFor(model => model.Package.State, new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"}
},
"value",
"text",
2))
With produces this:
<select id="Package_State" name="Package.State"><option value="0">Red</option>
<option value="1">Blue</option>
<option value="2">Green</option>
</select>
The model => model.Package.State expression is used to generate the id and name on the select.
The string value and text matter as they need to match the model attributes of the listItem in the list.
Or you can create your own List collection (with different fields for value and text) in your controller, set it on you model, and then use in your view like this:
#Html.DropDownListFor(model => model.Package.State.Id, new SelectList(
Model.PackageStates,
"id",
"name",
Model.Package.State.Id))

Having two values on SelectList() in asp.net

I'm trying to develop a website using asp.net mvc 4 & EF6 where I'm using dropdownlist to assign datas to my required textboxes. So far I've managed to assign data to two textboxes where one holds the value of the selected item of dropdownlist & one holds the text given for the selected item. But I need to add another value from the selected item. My codes are below,
Controller
ViewBag.Clients = new SelectList(db.ClientInfoes, "age", "fullname"); //This is given
ViewBag.Clients = new SelectList(db.ClientInfoes, "id", "age", "fullname"); //I want something like this
View
#Html.DropDownList("Clients", "Select...")
// Textboxes are populated automatically by using jQuery
#Html.TextBoxFor(a => a.Fullname, new { id = "clientName", #readonly = "readonly" })
#Html.TextBoxFor(a => a.Age, new { id = "clientAge", #readonly = "readonly" })
How can I assign more than one value in the SelectList? Any way I can do that would be fine. Need this help badly. Thanks.
It looks like you want to show name and age both in the dropdown text, in that case you need to project the result coming from database :
var ClientInfoes = db.ClientInfoes
.Select(x=>
new {
id = x.id,
name = x.fullname+","+x.age
});
ViewBag.Clients = new SelectList(ClientInfoes, "id", "name");

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

While binding dropdown in MVC, I always get this error: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country.
View
#Html.DropDownList("country", (IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country")
Controller
List<Companyregister> coun = new List<Companyregister>();
coun = ds.getcountry();
List<SelectListItem> item8 = new List<SelectListItem>();
foreach( var c in coun )
{
item8.Add(new SelectListItem
{
Text = c.country,
Value = c.countryid.ToString()
});
}
ViewBag.countrydrop = item8;
return View();
I don't know how to resolve it.
If you were using DropDownListFor like this:
#Html.DropDownListFor(m => m.SelectedItemId, Model.MySelectList)
where MySelectList in the model was a property of type SelectList, this error could be thrown if the property was null.
Avoid this by simply initializing it in constructor, like this:
public MyModel()
{
MySelectList = new SelectList(new List<string>()); // empty list of anything...
}
This often happens in POST actions. Make sure you assign something before re-rendering the view.
In your action change ViewBag.countrydrop = item8 to ViewBag.country = item8;and in View write like this:
#Html.DropDownList("country",
(IEnumerable<SelectListItem>)ViewBag.country,
"Select country")
Actually when you write
#Html.DropDownList("country",
(IEnumerable)ViewBag.country,
"Select country")
or
Html.DropDownList("country","Select Country)
it looks in for IEnumerable<SelectListItem> in ViewBag with key country, you can also use this overload in this case:
#Html.DropDownList("country","Select country") // it will look for ViewBag.country and populates dropdown
See Working DEMO Example
Note that a select list is posted as null, hence your error complains that the viewdata property cannot be found.
Always reinitialize your select list within a POST action.
For further explanation:
Persist SelectList in model on Post
try this
#Html.DropDownList("ddlcountry",(List<SelectListItem>)ViewBag.countrydrop,"Select country")
In Controller
ViewBag.countrydrop = ds.getcountry().Select(x => new SelectListItem { Text = x.country, Value = x.countryid.ToString() }).ToList();
Try This.
Controller:
List<CountryModel> countryList = db.countryTable.ToList();
ViewBag.Country = new SelectList(countryList, "Country", "CountryName");
I had a the same problem and I found the solution that I should put the code to retrieve the drop down list from database in the Edit Method. It worked for me.
Solution for the similar problem
In my case, the error occurred because I had not initialized the select list in the controller like this:
viewModel.MySelectList = new List<System.Web.Mvc.SelectListItem>();
As none of the existing answers made this clear to me, I post this. Perhaps it helps anybody.
your code is correct because in some cases it does not work, I also do not know where the error comes from but this can help you solve the problem, move the code in the head of the view like this:
index.cshtml:
#using expert.Models;
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
Manager db = new Manager();
ViewBag.FORM_PRESTATION = new SelectList(db.T_BDE_PRESTATION_PRES.OrderBy(p => p.PRES_INTITULE).Where(p => p.T_B_PRES_ID == null), "PRES_ID", "PRES_INTITULE");
}
<div class="form-group">
<label class = "w3-blue" style ="text-shadow:1px 1px 0 #444">Domaine:</label>
<div class="col-md-10">
#Html.DropDownList("FORM_PRESTATION", null, htmlAttributes: new { #class = "w3-select ", #required = "true" })
</div>
</div>
you can use this:
var list = new SelectList(countryList, "Id", "Name");
ViewBag.countries=list;
#Html.DropDownList("countries",ViewBag.countries as SelectList)
Replace "country" with "countrydrop" in your view like this...
#Html.DropDownList("countrydrop", (IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country")
Could be like for ASP.NET MVC Framework
#Html.DropDownList("country", ViewBag.countrydrop as List<SelectListItem>,"Select country")
or ASP.NET Core MVC
<select class="class" id="country"
asp-items="#(new SelectLits(ViewBag.countrydrop,"Value","Text"))">
You are facing this problem because when you are posting your forms so after reloading your dropdown is unable to find data in viewbag. So make sure that code you are using in get method while retrieving your data from db or from static list, copy paste that code into post verb as well..
Happy Coding :)

Categories

Resources