Get values from Dropdown list MVC values - c#

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?

Related

Reloading the webpage will make the dropdownlist null

I am trying to load all the database agents into a dropdown list, and I want to insert the selected id into another table. Dropdown list function and insert functions are working, but after the page reload, the dropdown list return as null, and I am getting this error There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key AssignPerson The code is mentioned below
View
#Html.DropDownListFor(m => m.AssignPerson, (IEnumerable<SelectListItem>)ViewBag.users, "Select Assign Person", new { #class = "form-control", #required = "required" })
Controller
public ActionResult NewAccess()
{
List<Agent> countryList = _context.Agents.ToList();
ViewBag.users = new SelectList(countryList, "AgentID", "AgentName");
return View();
}

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]

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

i want to add onchange event to my dropdownlist

The problem is that I have a form, inside this form I have dropdownlist which contain name of a student which comes from a database and I want to submit form every time I select any value from this dropdownlist. When I try this code:
#Html.DropDownList("StudentId", "--Select Students--", new { onchange = "this.form.submit();" })
An error appears to me:
StudentId is a ViewBag containing List of Students come from
database in controller action
try this:
new { #onchange = "this.form.submit();" })

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

Categories

Resources