How to select values inside list? - c#

How to select values inside MultiSelect? I just want to select some items inside a dropdownlist from URL Variables
Issue: following line is not selecting items Colors.add(TempArray[i]);
debug: If I remove this line than it works ok and selects values. if (!string.IsNullOrEmpty(result)) ... foreach (var item2 in TempArray) but I need this line to check for null values. Code will get error otherwise
Also If I remove Post Method and it goes to Get directly than it works fine (items get selected). how can I make it work by using post method
Form
<form asp-page="./Index" method="post">
<select asp-for="Colors" asp-items="#Model.Colors_SELECT " class="MultiSelect" multiple>
....
</select>
...
back-end variables
[BindProperty(SupportsGet = true)]
public List<string>? Colors { get; set; }
public SelectList? Colors_SELECT { get; set; }
OnPost() Method - here I am change the URL format. for ex: localhost/index?Colors=red&Colors=Black to localhost/index?Colors=red,Black
public async Task<IActionResult> OnPostAsync()
{
var CurrentFilters = new Dictionary<string, string>();
var ColorsTemp = string.Join(",", Colors);
CurrentFilters.Add("Colors", ColorsTemp);
string query = "";
foreach (var p in CurrentFilters)
{
query += $"{p.Key}={p.Value}&";
}
query = query.TrimEnd(query[query.Length - 1]); //remove last '&'
var url = $"{HttpContext.Request.Path}?{query}"; // create URL
return Redirect(url); // Send new url - call get Method()
}
on OnGet() method
public async Task OnGetAsync()
{
// here i want to get URL values and select those items
string result = Request.Query["Colors"];
if (!string.IsNullOrEmpty(result))
{
string[] TempArray = result.Split(",");
foreach (var item2 in TempArray)
{
Colors.add(TempArray[i]);
}
}
}

Related

How to populate a class with a C# String List

In the system I'm developing I send a select with multiple options to a string type list in my controller, I now need to link this list that I get from the view to the list with the login class I have in my model. The goal is that each position in the string list becomes a position in the new list.
For example I get the following list with the values that were sent from the view select:
[0] = "147"
[1] = "33"
I need to link this array to my other login list, something like this
Login[0] = "147
Login[1] = "33"
I'll put my codes with comments to explain it better:
View:
<select class="selectpicker" multiple data-live-search="true" asp-for="ListResponsibles">
<option value="147">John</option>
<option value="212">Maria</option>
<option value="33">Luiza</option>
</select>
Model:
//Here I get the options marked in the select
public List<string>ListResponsibles { get; set; }
//I want to pass the list I received from the view to this list
public List<Responsibles> ListResponsiblesData { get; set; }
public class Responsibles
{
public string Login { get; set; }
}
Controller:
public async Task<IActionResult> RegisterTask([FromForm] WebdeskTasks webdeskTasks)
{
//I created this variable to receive data from the other list
var LoginList = webdeskTasks.ListResponsiblesData;
//Here I tried to link each possibility of the view's list array to my list, but it doesn't show value in webdeskTarefas.ListResponsibles [i]
for (int i = 0; i < webdeskTasks.ListResponsibles.Count; i++)
{
LoginList[i].Login = webdeskTasks.ListResponsibles[i];
}
Or the LINQish way:
public async Task<IActionResult> RegisterTask([FromForm] WebdeskTasks webdeskTasks)
{
webdeskTasks.ListResponsiblesData = webdeskTasks.ListResponsibles
.Select(entry => new Responsible { Login = entry })
.ToList();
//....
}
You can try following code:
public async Task<IActionResult> RegisterTask([FromForm] WebdeskTasks webdeskTasks)
{
var LoginList = new List<Responsibles>();
foreach (string i in webdeskTasks.ListResponsibles)
{
Responsibles re = new Responsibles();
re.Login = i;
LoginList.Add(re);
}
webdeskTasks.ListResponsiblesData = LoginList;
//....
}

Is this possible to add async function result into table row?

I'm creating web-client for my REST API, and I want to add a field to my table containing result of async function.
#foreach(Product item in products)
{
<tr>
<th>#item.Name</th>
<th>#item.Amount</th>
<th>#GetUnit(item.UnitID).Result</th>
<th>#item.PriceNetto</th>
</tr>
}
async Task<string> GetUnit(Guid id)
{
string a = "https://localhost:5001/api/Units/";
a += id.ToString();
var temp = await Http.GetJsonAsync<Unit>(a); //it fails here
return temp.Name;
}
In short I have a list of products and items on the list have "UnitID" property which I use to make a GET request. When I put anywhere in code .Result after my async function result Visual Studio's debugger just skip the line responsible for calling the API and 'bricks' whole app without any error nor exception. Then I have to restart the project.
I tried to create second function only for returning GetUnit(id).Result but it gave nothing. I tried to return whole Unit object and then in the table GetUnit(item.UnitID).Name but it was just representing object (I guess...). I seems like all I need is do it with .Result but when I do it doesn't work.
My API is made with .Net Core 2.2 and my client is made with .Net Core 3.0 (Blazor template). Is this a bug or I just can't do it that way? Thanks.
you shouldn't need to do it.i recommand to call it in async action,like below :
razor focus on view,controller/model focus on data.
public async Task<IActionResult> SomeAction(Guid id)
{
var products = ..;
foreach (var item in products)
{
p.UnitID = await GetUnit(item.UnitID);
}
return View(products);
}
private async Task<string> GetUnit(Guid id)
{
string a = "https://localhost:5001/api/Units/";
a += id.ToString();
var temp = await Http.GetJsonAsync<Unit>(a); //it fails here
return temp.Name;
}
public class Product
{
public string Name { get; set; }
public decimal Amount { get; set; }
public string UnitID { get; set; }
public string PriceNetto { get; set; }
}
IMO, you can't do that way.In blazor,you could get all data in OnInitializedAsync instead.Store all Name in a string List and display the list data in view based index.For example:
#code {
private List<string> listItems = new List<string>();
protected override async Task OnInitializedAsync()
{
//get products
foreach (var product in products)
{
string a = "https://localhost:5001/api/Units/";
a += product.UnitID.ToString();
var temp = await Http.GetJsonAsync<Unit>(a);
listItems.Add(temp.Name);
}
}
}
Razor
#{ int i = 0;}
#foreach(Product item in products)
{
<tr>
<th>#item.Name</th>
<th>#item.Amount</th>
<th> #listItems[i] </th>
<th>#item.PriceNetto</th>
</tr>
i++;
}

Items in picker from a list - Xamarin Code behind

I am stuck on how to show items from a list in a picker.
I can use a for loop and add the items to the Picker, is there any other way ? I have to also use bound values from the list. All I get right now is the type and not the ID or Category name i need.
Image of what I see...
private async void GetCategories(string url)
{
//get json as a string
var result = await _clientHttp.GetStringAsync(url);
var json = JsonConvert.DeserializeObject<List<CategoryList>>(result);
List<CategoryList> tempList = new List<CategoryList>();
foreach (var items in json)
{
tempList.Add(new CategoryList{CatId = items.CatId,category = items.category});
}
;
PickerCategory.ItemsSource = tempList;
}
You must override your CategoryList.ToString() method to display the appropriate values:
class CategoryList{
public string category {get;set;}
public override string ToString(){
return category;
}
}

DropDownListFor has unique value for all items

I am using a razor helper DropDownListFor in order to have a dropdown list of Organizational Units from Active Directory (replicated in Database, it doesn't matter so much). The idea is you have a first list with all parent elements, and when clicking, I search my database to find the children elements, and so on until you reach a leaf (so to speak, last element). My problem is that when inspecting element in my browser I find that all value from the <option> markup are equal to the first id that I pass when clicking.
So here is my ViewModel:
public class SiteDirectionModel
{
public int id { get; set; }
public List<SelectListItem> Names { get; set; }
}
Then my first controller method (for parent elements) is the following :
public ActionResult CreateADUser()
{
List<SelectListItem> items = new List<SelectListItem>();
SiteDirectionModel sdM = new SiteDirectionModel();
//The below method gets all parent nodes from database
//_nonGenService is an instance of a service that can access my Repository
direction = _nonGenService.GetAllSiteDirection();
if (direction != null && direction.Count!=0)
{
items.Add(new SelectListItem
{
Text = dir.Name,
Value = dir.IDDirection.ToString()
});
}
sdM.Names = items;
return View(sdM);
}
else
return View("AccessError"); //A page in case of error
}
Then the second controller method to treat child elements:
public ActionResult GetSiteRF(SiteDirectionModel model)
{
SiteDirectionModel sdM = new SiteDirectionModel();
List<SelectListItem> items = new List<SelectListItem>();
//This method gets children elements from a specified id
//The table that looks has IDDirection as FK from first table
radioFrance = _nonGenService.GetSiteRFFromDirection(model.id);
direction = _nonGenService.GetAllSiteDirection();
int id;
string nameConcat = string.Empty;
//For loop to concatenate names
foreach(var dir in direction)
{
if (dir.IDDirection == model.id)
{
nameConcat = dir.Name + "-" + nameConcat;
break;
}
}
if (radioFrance.Count==1)
{//This condition would be to see if the name is equal to the current node so
//that we can exit the condition and access a form to create the user
Site_RadioFrance single = radioFrance.SingleOrDefault();
if (single.Name.Equals(nameConcat))
{
return View("CreateADForm", model);
}
}
else
{
foreach (var radio in radioFrance)
{
items.Add(new SelectListItem
{
Text = nameConcat+radio.Name,
Value = radio.IDDirection.ToString()
});
}
sdM.Names = items;
return View("CreateADUser",sdM);
}
return View("AccessError"); //Error treatement
}
My view loks like this :
#model MyProject.Models.SiteDirectionModel
<h2>Create an account in Active Directory</h2>
#using (Html.BeginForm("GetSiteRF", "Create", FormMethod.Post))
{
#Html.DropDownListFor(x => x.id, Model.Names);
<input type="submit" value="Selectionner" class="btn btn-primary"/>
}
Now say you have the item clicked with IDDirection=10 then all my child elements have
<option value=10>parent1-child1</option>
<option value=10>parent1-child2</option>
<option value=10>parent1-child3</option>
<option value=10>parent1-child4</option>
I don't know how to fix this, any ideas? because then my model id has this value, and I somehow thought that it would apply a value for each different option, I don't understand why it doesn't?
Thanks!

Set selected value in dropdown list

How do I set the selected value on a drop down list? Here is what I have so far:
#model Web.Models.PostGraduateModels.PlannedSpecialty
#Html.DropDownList("PlannedSpecialtyID")
//controller
[HttpGet]
public PartialViewResult PlannedSpecialty()
{
// Get Planned Specialty ID
var pgtservice = new PgtService();
PostGraduateModels.PlannedSpecialty plannedSpecialty = pgtservice.GetPlannedSpecialtyId();
// Get Data for Planned Specialty DropDown List from SpecialtyLookup
var pgtServ = new PgtService();
var items = pgtServ.GetPlannedSpecialtyDropDownItems();
ViewBag.PlannedSpecialtyId = items;
return PartialView(plannedSpecialty);
}
// service
public IEnumerable<SelectListItem> GetPlannedSpecialtyDropDownItems ()
{
using (var db = Step3Provider.CreateInstance())
{
var specialtyList = db.GetPlannedSpecialtyDdlItems();
return specialtyList;
}
}
// data access
public IEnumerable<SelectListItem> GetPlannedSpecialtyDdlItems()
{
IEnumerable<Specialty> specialties = this._context.Specialties().GetAll();
var selList = new List<SelectListItem>();
foreach (var item in specialties)
{
var tempps = new SelectListItem()
{
Text = item.Description,
Value = item.Id.ToString()
};
selList.Add(tempps);
}
return selList;
}
I would recommend you to avoid using ViewBag/ViewData/ Weekly typed code. Use strongly typed code and it makes it more readable. Do not use the Magic strings/ Magic variables. I would add a collection property to your ViewModel to hold the SelectList items and another property to hold the selected item value.
public class PlannedSpecialty
{
public IEnumerable<SelectListItem> SpecialtyItems { set;get;}
public int SelectedSpeciality { set;get;}
//Other Properties
}
and in your Get action, If you want to set some Item as selected,
public PartialViewResult PlannedSpecialty()
{
var pgtServ = new PgtService();
var vm=new PlannedSpecialty();
vm.SpecialtyItems = pgtServ.GetPlannedSpecialtyDropDownItems();
//just hard coding for demo. you may get the value from some source.
vm.SelectedSpeciality=25;// here you are setting the selected value.
return View(vm);
}
Now in the View, use the Html.DropDownListFor helper method
#Html.DropDownListFor(x=>x.SelectedSpeciality,Model.SpecialtyItems,"select one ")
Use the selected property of the SelectListItem class:
selList.Selected = true;

Categories