Having two values on SelectList() in asp.net - c#

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");

Related

How to set default value for ASP.NET MVC DropDownList from ViewBag

In the controller Index I have the following:
ViewBag.Assignees = (await GetAllUsers()).Select(a =>
new SelectListItem
{
Text = a.DisplayName,
Value = a.Username,
Selected = a.DisplayName == "John Smith"
}).OrderBy(x => x.Text).ToList();
In the View, I have the following:
#Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Select Assignee",
new { id = "ddlAssignee", #class = "form-control"})
The dropdownlist populates as expected, however, the default (selected = true) value, which does exist, does not get set. Can someone advise what is wrong in the above?
UPDATE:
By Changing the SelectListItem.Value to a.DisplayName (same as SelectedListItem.Text) I achieved it. Still not sure what prevents the dropdownlist from displaying the item with Selected = true
If the model.Assignee comes with value, and if it is an int it will be defaulted to 0, it will override the SelectListItem selected value.
I suggest to set up the model.Assignee.
Here two ways that i use.
WAY 1
#Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Value", // property to be set as Value of dropdown item
"Text", // property to be used as text of dropdown item
"1"), // value that should be set selected of dropdown
new { id = "ddlAssignee", #class = "form-control"})
WAY 2
<select name="SelectName" value="1" class="w-100">
#foreach (var item in ViewBag.Collection) {
<option value="#item.Id">#item.Name</option>
}
</select>
I hope it work for you
#Html.DropDownListFor how to set default value
In your view set:
#Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Select Assignee",
new { id = "ddlAssignee", #class = "form-control", #value = "Default value"})
When you have list already defined.
Use This
#Html.DropDownList("CoverageDropDown", new SelectList(Model.youList, "Code", "Description",item.seletecItem), "Select")

Get values from Dropdown list MVC values

I'm using the following piece of code to get a list of values.
using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
{
var groups = await client.Groups.GetGroupsAsync();
List<PowerBIGroups> groupList = new List<PowerBIGroups>();
foreach (var group in groups.Value)
{
groupList.Add(new PowerBIGroups() { Id = group.Id, Name = group.Name });
}
return View(groupList);
}
And in the view at the top I'm declaring the model as:
#model IEnumerable<PowerBIEmbedded.Models.PowerBIGroups>
To get the values of the dropdown list:
#Html.DropDownList("groupId", new SelectList(Model.Select(k => k.Name)), "-- Select Group --", new { #class = "form-control", onchange = #"var form = document.forms[0]; form.action= 'GetUser'; form.submit();" })
See here, I'm able to get the values of the list in a a dropdown. But how do I get the value of Id associated with it, that I'm adding in the controller? Also, how do I get the Id in the code behind?
Using this piece of code in the onChange event in the dropdown list:
onchange = #"var form = document.forms[0]; form.action= 'GetUser'; form.submit();" } I'm able to invoke the GetUser method inside the controller with the parameters as the Name property.
How can I get the value of Id here.
One more issue associated with this is that I've to run the application from index.html where the GetUser method is invoked otherwise it is giving me a 404 not found error.
How can I fix this?

MVC how to change dropdownlist item names

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]

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" })

Getting Disabled Dropdown values in MVC

I am pretty new to MVC. In my form i have a disabled dropdown control whose value is not getting passed to the Model during submit as it is disabled. I tried using a hidden field like below
#Html.DropDownListFor(model => model.DepartmentID, new List<SelectListItem> { new SelectListItem { Text = "Item 1", Value = "1" }, new SelectListItem { Text = "Item 2", Value = "2", Selected = true } })
#Html.HiddenFor(model => model.DepartmentID)
Both of the above statement produce controls having the same id so i was not sure can i get the value of the dropdown in the hidden field.
I could use a different id while creating the hidden variable and assign the dropdown value it it using jquery.
I just want to know if i can achieve the same using the Hidden field having the same id as shown in the above code ??
Form Fields are not submitted by ID, they're submitted by name. It's ok for there to be two controls with the same name. However, it's invalid HTML to have two elements with the same id.
You can set a different ID but keep the same name like this:
#Html.HiddenFor(x => x.DepartmentID, new { id="DepartmentID2" })

Categories

Resources