in my class menu code and description name
namespace Test.Controllers
{
class menus
{
public string Idmenus { get; set; }
public string desname { get; set; }
}
}
in my controller I want to add data to object List
var viewdes = db.menudescriptions.Where(w => w.Idmenu == mids).ToList();
var desc = new List<menus>();
foreach (var b in viewdes) {
desc.Add(new menus { Idmenus = b.Iddesmenu });
desc.Add(new menus { desname = b.descriptionname });
}
if ((desc.Count != 0))
{
ViewBag.Id = desc.ToList();
}
I want to show ViewBag.Id To Viewpage?
#if (ViewBag.Id != null)
{
<td>
#foreach (var per in `enter code here`)
{
#Html.ActionLink(#per.ToString(), "detail", new { mides = per })
}
</td>
}
You basically just need to iterate your ViewBag.Id like what you normally do when using foreach
#foreach(var per in ViewBag.Id as List<menus>)
{
#Html.ActionLink(per.desname, "detail", new { mides = per })
}
Related
Trying to bind to a multiple selection values in Blazor.
Frontend shows this:
<div class="form-group col-sm-4">
#foreach (var tagName in TagSelection)
{
<label>
#tagName.Name:
<select multiple>
#foreach (var value in tagName.Values)
{
<option value="#value.Name">#value.Name</option>
}
</select>
</label>
<br>
}
<br>
</div>
I don't even know where to begin to be able to bind to the multiple selection event. Saving question for now until further research but would appreciate any resources 😊
Thanks.
Here is a working demo to bind multiple select values(bind data to SelectedValues in Tag class):
Counter.razor:
#page "/counter"
<h1>Counter</h1>
<form>
<div class="form-group col-sm-4">
#{ var count = 0;}
#foreach (var tagName in TagSelection)
{
<div>
<label>
#TagSelection[count].Name:
#{ var id = "id" + count; }
<SelectMultiple uniqueID="#id" #bind-values="tagName.SelectedValues" multiple="#(true)" update="update" classNames="#("form-control")">
#foreach (var value in tagName.Values)
{
<option value="#value.Name">#value.Name</option>
}
</SelectMultiple>
#if (tagName.SelectedValues == null || tagName.SelectedValues.Count == 0)
{
<h3>No Tags selected!</h3>
}
else
{
#foreach (var item in tagName.SelectedValues)
{
<span> #item |</span>
}
}
</label>
#{count++;}
</div>
}
<br>
</div>
</form>
#code {
[Parameter]
public List<Tag> TagSelection { get; set; } = new List<Tag> {
new Tag { Name = "tag1", Values = new List<Value> { new Value { Name = "tag1_value1" }, new Value { Name = "tag1_value2" }, new Value { Name = "tag1_value3" } } } ,
new Tag { Name = "tag2", Values = new List<Value> { new Value { Name = "tag2_value1" }, new Value { Name = "tag2_value2" }, new Value { Name = "tag2_value3" } } } ,
new Tag { Name = "tag3", Values = new List<Value> { new Value { Name = "tag3_value1" }, new Value { Name = "tag3_value2" }, new Value { Name = "tag3_value3" } } }
};
void update(string newMessage)
{
StateHasChanged();
}
public class Tag
{
public string Name { get; set; }
public List<Value> Values { get; set; }
public List<string> SelectedValues { get; set; } = new List<string>();
}
public class Value
{
public string Name { get; set; }
}
}
Shared/SelectMultiple.razor:
#typeparam TItem
#inject IJSRuntime jsRuntime
<select id="#uniqueID" class="#classNames" multiple="#multiple" #onchange="OnChange" style="height: 145px;">
#if (title != null)
{
<option selected disabled value="null">#title</option>
}
<CascadingValue name="Dropdown" Value="#this">
#ChildContent
</CascadingValue>
</select>
#code {
[Parameter]
public string ID { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public List<TItem> values { get; set; }
[Parameter]
public Action<List<TItem>> valuesChanged { get; set; }
[Parameter] public EventCallback<string> update { get; set; }
[Parameter]
public string title { get; set; }
[Parameter]
public bool multiple { get; set; }
[Parameter]
public string classNames { get; set; }
[Parameter]
public string uniqueID { get; set; }
private static T ConvertByType<T>(object obj)
{
if (obj is T)
{
return (T)obj;
}
try
{
return (T)Convert.ChangeType(obj, typeof(T));
}
catch (InvalidCastException)
{
return default(T);
}
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
}
await jsRuntime.InvokeAsync<object>("dropdown.custom_select", uniqueID, String.Join(",", values), multiple);
}
public void OnChange(ChangeEventArgs e)
{
jsRuntime.InvokeVoidAsync("dropdown.onOptionSelect", DotNetObjectReference.Create(this), uniqueID);
}
[JSInvokable("onOptionSelect")]
public async Task<bool> onOptionSelect(string selectId, List<string> selectedValues)
{
try
{
if (values != null)
{
values = selectedValues.Select(x => ConvertByType<TItem>(x)).ToList();
}
else
{
values.Clear();
}
valuesChanged.Invoke(values);
StateHasChanged();
await update.InvokeAsync("Hello from ChildComponent");
return await Task.FromResult(true);
}
catch
{
return await Task.FromResult(false);
}
}
}
blazor.server.js:
window.dropdown = {
custom_select: function (id, values, multiple) {
if (values != undefined) {
if (multiple) {
if (Array.isArray(values)) {
var selectValues = values;
}
else {
var selectValues = values.split(',');
}
var selector = '#' + id + ' option';
/* Iterate options of select element */
for (const option of document.querySelectorAll(selector)) {
/* Parse value to integer */
const value = option.value;
/* If option value contained in values, set selected attribute */
if (selectValues.indexOf(value) !== -1) {
option.setAttribute('selected', 'selected');
}
/* Otherwise ensure no selected attribute on option */
else {
option.removeAttribute('selected');
}
}
}
else {
document.getElementById(id).value = values;
}
}
},
getSelectValues: function (select) {
var result = [];
var options = select && select.options;
var opt;
for (var i = 0, iLen = options.length; i < iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
},
onOptionSelect: function (dotNetObject, selectId) {
var values = dropdown.getSelectValues(document.getElementById(selectId));
dotNetObject.invokeMethodAsync('onOptionSelect', selectId, values);
},
}
Add <script src="~/js/blazor.server.js"></script> to Pages/_Host.cshtml.
result:
Unclear on how to pass this model to my view.
I have a list model being passed into my view. But I want to separate the Participant's inside the list depending on which User is logged in on the ViewBag.
current view code (working):
this code works as it should but its not separating the participants depending on what user is logged in. it displays the entire list. I'm getting red squilies under #model, League inside my foreach line, and MMLeagueParticipants in my secondforeach. But it still worked.
error:
when I hovered over #model and League:
The type or namespace name 'League' could not be found (are you missing a using directive or an assembly reference?)[LeagueProect]
When I hovered over MMLeagueParticipant:
The type or namespace name 'MMLeagueParticpant' could not be found (are you missing a using directive or an assembly reference?`
//RED SQUIGLY #1 #model
#model List<League>
#{
if (Model != null && Model.Any())
{
//RED SQUIGLY #2 League
foreach(League i in Model)
{
//RED SQUIGLY #3 MMLeagueParticipant
foreach (MMLeagueParticipant mmLeagueParticipant in i.allParticipants)
{
<p>#mmLeagueParticipant.child.ParticipantFirstName #mmLeagueParticipant.child.ParticipantLastName</p>
}
}
}
else
{
<p>the list is empty</p>
}
}
Attempt to separate (not working)
still using #model List<League>.
When I change my code to try and separate it crashes entirely
<p>Your kid(s):</p>
if (Model != null && Model.Any())
{
foreach(League i in Model)
{
var userParticipants = i.allParticipants.Where(p => p?.child?.Parent?.UserId == ViewBag.UserId).ToList();
foreach (MMLeagueParticipant mmLeagueParticipant in userParticipants)
{
<p>#mmLeagueParticipant.child.ParticipantFirstName #mmLeagueParticipant.child.ParticipantLastName</p>
}
}
}
<p>not your kid(s):</p>
if (Model != null && Model.Any())
{
foreach(League i in Model)
{
var userParticipants = i.allParticipants.Where(p => p?.child?.Parent?.UserId != ViewBag.UserId).ToList();
foreach (MMLeagueParticipant mmLeagueParticipant in userParticipants)
{
<p>#mmLeagueParticipant.child.ParticipantFirstName #mmLeagueParticipant.child.ParticipantLastName</p>
}
}
}
The error I get from trying this:
NullReferenceException: Object reference not set to an instance of an object.
It doesn't like the lines:
var userParticipants = i.allParticipants.Where(p => p.child.Parent.UserId == ViewBag.UserId).ToList();
#await Html.PartialAsync("_Displayeach", Model["bbM7and8"])
I'm assuming the way I'm passing in the model to my view is incorrect. But entirely unsure why one way is working and the other isn't.
Controller details:
in my controller I have a list of age groups that i add new participant models to.
Then I pass the list to my RosterPageBasketball view.
Inside that view I have 12 tabs; each displaying differnt lists depending on the age group.
model used in RosterPageBacketball: #model List<League>
Each tab in the RosterPageBasketball that displays different agegroups:
#await Html.PartialAsync("_Displayeach", Model["bbM7and8"])
_displayeach is my Current view code
The tabs were working as needed when showing all Participants with my Current view code (as showed above) with their own list of different age groups when I wasn't sperating the participants depending on if they belong to the logged on user or not.
each tab in my RosterPageBasketballcontains the following code: #await Html.PartialAsync("_Displayeach", Model["bbM#and#"])
where I thought the issue might be:
("_Displayeach", Model["bbM7and8"])
the model I'm sending to my partial is Model["bbM7and8"] but the model I'm using in my _Displayeach is #model List<League>. unsure how or if it's possible to pass in #model Dictionary<string, List<League>>.
controller:
public async Task<IActionResult> GetBasketballRoster()
{
String[] leagueNames = new[]
{
"bbM7and8",
"bbM9and10",
"bbM11and12",
"bbM13and14",
"bbM15and16",
"bbM17and18",
"bbF7and8",
"bbF9and10",
"bbF11and12",
"bbF13and14",
"bbF15and16",
"bbF17and18"
};
Dictionary<string, List<League>> d = new Dictionary<string, List<League>>();
foreach (var name in leagueNames)
{
List<League> bbLeagues = await db.Leagues
.Where(l => l.sport == "Basketball")
.Where(l => l.ageRange==name)
.ToListAsync();
foreach (League league in bbLeagues)
{
List<MMLeagueParticipant> leagueParticipants = await db.Entry(league)
.Collection(l => l.allParticipants)
.Query() // <-- This is needed to allow for `Include()`
.Include(mmp => mmp.child)
.ToListAsync();
}
d.Add(name,bbLeagues);
}
return View("RosterPageBasketball", d);
}
Dictionary<string, List> d is passed to the RosterpageBasketball
_Displayeach view is passes a model["bbM#and#"]
_Displayeach view uses #model List<League>
From your code, it seems you want to display List<League> which is in partial view for specific ageRange.
Here is a working demo you could follow:
Model:
public class League
{
public string sport { get; set; }
public string ageRange { get; set; }
public List<MMLeagueParticipant> allParticipants { get; set; }
}
public class MMLeagueParticipant
{
public child child { get; set; }
}
public class child
{
public string ParticipantFirstName { get; set; }
public string ParticipantLastName { get; set; }
}
RosterPageBasketball.cshtml:
#model Dictionary<string, List<League>>
#{
var data = Model.Where(a => a.Key == "bbF17and18").Select(a => a.Value).FirstOrDefault();
}
#await Html.PartialAsync("_Displayeach", data)
_Displayeach.cshtml:
#model List<League>
#{
if (Model != null && Model.Any())
{
foreach (League i in Model)
{
foreach (MMLeagueParticipant mmLeagueParticipant in i.allParticipants)
{
<p>#mmLeagueParticipant.child.ParticipantFirstName #mmLeagueParticipant.child.ParticipantLastName</p>
}
}
}
else
{
<p>the list is empty</p>
}
}
Controller:
public async Task<IActionResult> Index()
{
String[] leagueNames = new[]
{
"bbM7and8",
"bbM9and10",
"bbM11and12",
"bbM13and14",
"bbM15and16",
"bbM17and18",
"bbF7and8",
"bbF9and10",
"bbF11and12",
"bbF13and14",
"bbF15and16",
"bbF17and18"
};
Dictionary<string, List<League>> d = new Dictionary<string, List<League>>();
foreach (var name in leagueNames)
{
//hard coded the data....
List<League> bbLeagues = new List<League>()
{
new League(){sport="Basketball",ageRange="bbF17and18",allParticipants =new List<MMLeagueParticipant>(){ new MMLeagueParticipant() { child= new child() {ParticipantFirstName="San",ParticipantLastName="Da" } } } },
new League(){sport="Basketball",ageRange="bbF17and18",allParticipants =new List<MMLeagueParticipant>(){ new MMLeagueParticipant() { child= new child() {ParticipantFirstName="Api",ParticipantLastName="Ee" } } }},
new League(){sport="Basketball",ageRange="bbF9and10",allParticipants =new List<MMLeagueParticipant>(){ new MMLeagueParticipant() { child= new child() {ParticipantFirstName="May",ParticipantLastName="Fa" } } }},
new League(){sport="Basketball",ageRange="bbM17and18",allParticipants =new List<MMLeagueParticipant>(){ new MMLeagueParticipant() { child= new child() {ParticipantFirstName="Ben",ParticipantLastName="He" } } }},
new League(){sport="Basketball",ageRange="bbF15and16",allParticipants =new List<MMLeagueParticipant>(){ new MMLeagueParticipant() { child= new child() {ParticipantFirstName="Jun",ParticipantLastName="Pa" } } }},
new League(){sport="FootBall",ageRange="bbF15and16",allParticipants =new List<MMLeagueParticipant>(){ new MMLeagueParticipant() { child= new child() {ParticipantFirstName="Pen",ParticipantLastName="Me" } } }}
};
var data = bbLeagues.Where(l => l.sport == "Basketball").Where(l => l.ageRange == name).ToList();
d.Add(name, data);
}
return View("Index", d);
}
I want to group by vitaminlist, but it's not working.
My Model
public class SearchModel
{
public List<tbbesin> besinlist { get; set; }
public List<tbvitamin> vitaminliste { get; set; }
public List<tbmineral> mineralliste { get; set; }
}
My Controller
public ActionResult ara(BesinViewModel model)
{
var listegetir = model.besinler.Split(',');
List<tbbesin> besinliste = new List<tbbesin>();
List<tbmineral> minerallist = new List<tbmineral>();
List<tbvitamin> vitaminlist = new List<tbvitamin>();
SearchModel modelden = new SearchModel();
foreach (var item in listegetir)
{
var ID = int.Parse(item);
var besin = db.tbbesin.FirstOrDefault(x => x.besinid == ID);
var mineral = db.tbmineral.FirstOrDefault(x => x.besinid == ID);
var vitamin = db.tbvitamin.FirstOrDefault(x => x.besinid == ID);
vitaminlist.Add(vitamin);
minerallist.Add(mineral);
besinliste.Add(besin);
}
modelden.besinlist = besinliste.ToList();
modelden.mineralliste = minerallist.ToList();
modelden.vitaminliste = vitaminlist.ToList();
return View(modelden);
}
My View
#model WebApplication1.Models.SearchModel
#foreach (var item22 in Model.vitaminliste.
GroupBy(x => x.vitamindetayid).
Select(x=>x.First()).
ToList())
{
#item22.tbvitamindetay.vitaminad
}
I need to group by in view vitaminlist but its not working.
Why ? Can you help me what is a problem there
In view I want display data from list ucz and insert data to listaOcen. display the list of ucz works but I have no idea to input data into list listaOcen
#using biblioteka;
#model dynamic
<tr>
#for (int i = 0; i < Model.dl;i++ )
{
td>#Model.Uczniowie[i]</td>
<td>
#Html.DropDownList(Model.listaOcen[i], new[] { //doesnt work
new SelectListItem() { Text = "5", Value = "5" },
new SelectListItem() { Text = "4+", Value = "4.75" },
}, "Select option")
<td>
</tr>
}
Controller:
public ActionResult Add(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var dataContext = db.Uczniowie;
var ucz = dataContext.Where(m => m.KlasaId == id)
.Select(m => m.Nazwisko + " " + m.Imie);
List<double> listOfOcena = new List<double>();
dynamic mymodel = new ExpandoObject();
mymodel.Uczniowie = ucz.ToList();
mymodel.dl = ucz.ToList().Count;
mymodel.listaOcen = listOfOcena;// enter the data from DropDownLists
return View(mymodel);
It is model.
public class Ocena
{
public string IdUcznia { get; set; }
public string Id { get; set; }
public string Przedmiot { get; set; }
public double Wartosc { get; set; }
public double waga { get; set; }
public DateTime? Data { get; set; }
public string Rodzaj { get; set; }
public string Opis { get; set; }
}
Please help :)
Robert, first of all try to avoid dynamic model. Create a viemodel for your action. e.g.
public class StudentMarkAssignViewModel
{
public long StudentId { get; set; }
public string FullName { get; set; }
public double Mark { get; set; }
}
then fill it in your action
[HttpGet]
public ActionResult Add(string id)
{
var model = new StudentMarkAssignViewModel[]
{
new StudentMarkAssignViewModel {StudentId = 1, FullName = "Martin", Mark = 0 },
new StudentMarkAssignViewModel {StudentId = 2, FullName = "Robert", Mark = 5 }
};
//here i use hardcoded valuse, but you should get them from your db
return View(model);
}
after that you can render list of your students and assign them marks and submit it to the server
#using WebApplication100.Models
#model StudentMarkAssignViewModel[]
#using (Html.BeginForm("Add", "StudentMarks", FormMethod.Post))
{
<table>
#for (var index = 0; index < Model.Length; index++)
{
<tr>
#Html.HiddenFor(x => Model[index].StudentId)
#Html.HiddenFor(x => Model[index].FullName)
<td>#Model[index].FullName</td>
<td>
#Html.DropDownListFor(x => Model[index].Mark, new SelectListItem[]{
new SelectListItem{ Value = "0", Text = "Not Rated", Selected = Model[index].Mark == 0 } ,
new SelectListItem{ Value = "5", Text = "5" , Selected = Model[index].Mark == 5 } ,
new SelectListItem{ Value = "4.75", Text = "4+" , Selected = Model[index].Mark == 4.75 }
})
</td>
</tr>
}
</table>
<button type="submit">submit</button>
}
after you submit the form, you'll get list of students and their marks on the server
[HttpPost]
public ActionResult Add(StudentMarkAssignViewModel[] marksModel)
{
/* do whatever you need with your model*/
return RedirectToAction("Index");
}
that's all. I hope you'll get the point.
I am a beginner in ASP MVC, and, after a lot of help from SO, am progressing through ViewModels. Using a ViewModel however, I have encountered the following error.
Given the following View:
#model November.ViewModels.Staff_Salutation_VM
//...
using (Html.BeginForm("UpdateStaff", "Settings", FormMethod.Post,
new { #class = "clearfix parameter-form update-parameter update-staff", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
//...
#for (int i = 0; i < Model.AvailableStaffMembers.Count; i++)
{
var staff = Model.AvailableStaffMembers[i];
<tr>
<td>#Html.HiddenFor(model => staff.ID)#Html.ValueFor(model => staff.ID)</td>
<td>
#Html.DropDownListFor(
model => model.SalutationID, Model.AvailableSalutations.Select(option => new SelectListItem
{
Text = option.Desc.ToString(),
Value = option.ID.ToString(),
Selected = (option.ID.ToString() == staff.SalutationID.ToString())
}
),
"Choose...")
</td>
<td>#Html.EditorFor(model => staff.FName)</td>
<td>#Html.EditorFor(model => staff.LName)</td>
<td>#Html.EditorFor(model => staff.Active)</td>
<td>Delete</td>
</tr>
}
and the following Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using November.Models;
using November.ViewModels;
using November.DAL;
//...
//GET
var staffCreateViewModel = new Staff_Salutation_VM();
staffCreateViewModel.AvailableSalutations = new List<Prm_Salutation>();
var activeSalts = (from a in db.Prm_Salutations
where a.Active == true
orderby a.Desc ascending
select a);
staffCreateViewModel.AvailableSalutations = activeSalts.ToList();
staffCreateViewModel.AvailableStaffMembers = new List<Prm_Staff>();
var activeStaff = (from a in db.Prm_Staffs
where a.Active == true
orderby a.LName ascending
select a);
staffCreateViewModel.AvailableStaffMembers = activeStaff.ToList();
return View("StaffMembers", staffCreateViewModel);
//POST
public ActionResult UpdateStaff(Staff_Salutation_VM list)
{
if (ModelState.IsValid)
{
foreach (var formData in list) //no longer works due to dropping List<>
{
var tbl = db.Prm_Staffs.Where(a => a.ID.Equals(formData.ID)).FirstOrDefault();
if (tbl != null)
{
var Prm_StaffModel = new Prm_Staff();
Prm_StaffModel.SalutationID = formData.SalutationID;
Prm_StaffModel.FName = formData.FName;
Prm_StaffModel.LName = formData.LName;
Prm_StaffModel.Active = formData.Active;
}
}
db.SaveChanges();
ViewBag.UpdateRtrn = "Successfully Updated.";
return RedirectToAction("Parameters", new { param = "Staff Members" });
}
else
{
ViewBag.UpdateRtrn = "Failed ! Please try again.";
return RedirectToAction("Parameters", new { param = "Staff Members" });
}
}
return RedirectToAction("Parameters", new { param = "Staff Members" });
}
And, for good measure, the ViewModel itself:
public class Staff_Salutation_VM
{
public int ID { get; set; }
public int SalutationID { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public bool Active { get; set; }
public List<Prm_Salutation> AvailableSalutations { get; set; }
public List<Prm_Staff> AvailableStaffMembers { get; set; }
public Staff_Salutation_VM() { }
}
When triggered, no form values populate the ActionResult, resulting in a Object reference not set to an instance of an object. exception being thrown when the foreach (var formData in list) line is reached. Debugging shows list as being null. How can this be so? Or rather, what am I doing wrong?
EDIT: the list variable in my POST ActionResult is now getting data - or at least, is showing the various types in the class when debugged. How do I then iterate through it to save that data in the appropriate rows of the DB?
I totally missed the method signature, sorry! Your initial view load passes a model Staff_Salutation_VM but your UpdateStaff (form posted) is expecting List<Staff_Salutation_VM>. These are different animals. Change public ActionResult UpdateStaff(List<Staff_Salutation_VM> list) to public ActionResult UpdateStaff(Staff_Salutation_VM staff) just to see if you get past the null ref exception. Note, you'll need to remove your foreach since you don't have an IEnumerable coming in.
I hope this post will be helpful for you.
Model Binding To A List