MudSelect is not showing selected value - asp.net-core

I am facing issue with MudSelect with MultiSelect="true". Even though it has the selected values set it does not check the selected value:
<MudSelect Label="Select Item" SelectAll="true" MultiSelection="true" SelectedValues="#SelectedTestItems" T="#MultiSelectItem" ToStringFunc="#ToString">
#foreach (MultiSelectItem item in AllItems)
{
<MudSelectItem Value="#item" />
}
</MudSelect>
#code {
private List<MultiSelectItem> SelectedTestItems = new() {
new MultiSelectItem{Id = 1, Name = "Test 1"},
};
private List<MultiSelectItem> AllItems = new() {
new MultiSelectItem{Id = 1, Name = "Test 1"},
new MultiSelectItem{Id = 2, Name = "Test 2"},
new MultiSelectItem{Id = 3, Name = "Test 3"},
new MultiSelectItem{Id = 4, Name = "Test 4"},
};
private string ToString(MultiSelectItem x)
=> x is null ? string.Empty : $"{x.Name}";
public class MultiSelectItem
{
public int Id { get; set; }
public string Name { get; set; }
}
}
I posted details #github also: https://github.com/MudBlazor/MudBlazor/discussions/3532.

Your problem is that you did not override necessary methods for equality comparison. Here is a solution based on your snippet, you can play with it online: https://try.mudblazor.com/snippet/wYwPbGvKRlGThZsa
MudSelect uses a HashSet internally, so when you use custom reference types as values you must make sure they have GetHashCode and Equals based on their data:
<MudSelect Label="Select Item" SelectAll="true" MultiSelection="true" SelectedValues="#SelectedTestItems" T="#MultiSelectItem" ToStringFunc="#ToString">
#foreach (MultiSelectItem item in AllItems)
{
<MudSelectItem Value="#item" />
}
</MudSelect>
#code {
private List<MultiSelectItem> SelectedTestItems = new() {
new MultiSelectItem{Id = 1, Name = "Test 1"},
};
private List<MultiSelectItem> AllItems = new() {
new MultiSelectItem{Id = 1, Name = "Test 1"},
new MultiSelectItem{Id = 2, Name = "Test 2"},
new MultiSelectItem{Id = 3, Name = "Test 3"},
new MultiSelectItem{Id = 4, Name = "Test 4"},
};
private string ToString(MultiSelectItem x)
=> x is null ? string.Empty : $"{x.Name}";
public class MultiSelectItem
{
public int Id { get; set; }
public string Name { get; set; }
public override bool Equals(object o) {
var other = o as MultiSelectItem;
return other?.Id==Id;
}
public override int GetHashCode() => Id.GetHashCode();
}
}

Related

How to render custom HTML in Nonfactors/MVC6 grid

Since moving on from .net to .Net Core, Ive had to look for a WebGrid Replacement, which lead me to NonFactors MVC6 grid. I have gotten all the basic understanding of how all if works, now I am trying to understand how to use "#helper" function to display reusable HTML in the table.
Previously in .Net #helper allowed for defining customer HTML then using it in WebGrid, like so The Helper Function and the webgrid Webgrid. Now im currently learning how to do the same functionality in Razor Pages, and im currently at a dead end.
What I would Like to do, is using the MVC6 grid (Grid) with this custom checkbox (HTML)
When using the MVC6 Grid to add column, you could use the RenderedAs() and Html.Raw() method to add the checkbox. Code like this:
Model:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string MaritalStatus { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
public bool IsWorking { get; set; }
public bool IsSelected { get; set; }
}
public class PersonViewModel
{
public List<Person> Persons { get; set; }
public List<string> SelectedName { get; set; }
}
Controller:
public IActionResult Index3()
{
//Initial data.
var personvm = new PersonViewModel()
{
Persons = new List<Person>()
{
new Person() { Id = 1, Name = "Joe", Surname = "Crosswave", MaritalStatus = "Married", Age = 32, Birthday = DateTime.Now, IsWorking = false },
new Person() { Id = 2, Name = "Merry", Surname = "Lisel", MaritalStatus = "Widowed", Age = 42, Birthday = DateTime.Now, IsWorking = false },
new Person() { Id = 3, Name = "Henry", Surname = "Crux", MaritalStatus = "Single", Age = 29, Birthday = DateTime.Now, IsWorking = true },
new Person() { Id = 4, Name = "Cody", Surname = "Jurut", MaritalStatus = "", Age = 49, Birthday = DateTime.Now, IsWorking = false },
new Person() { Id = 5, Name = "Simon", Surname = "Scranton", MaritalStatus = "Single", Age = 34, Birthday = DateTime.Now, IsWorking = false },
new Person() { Id = 6, Name = "Leena", Surname = "Laurent", MaritalStatus = "Divorced", Age = 19, Birthday = DateTime.Now, IsWorking = false },
new Person() { Id = 7, Name = "Ode", Surname = "Cosmides", MaritalStatus = "Married", Age = 54, Birthday = DateTime.Now, IsWorking = true },
new Person() { Id = 8, Name = "Nicky", Surname = "Cassel", MaritalStatus = "Married", Age = 32, Birthday = DateTime.Now, IsWorking = true }
},
SelectedName = new List<string>() { "Merry", "Henry", "Leena", "Nicky" }
};
return View(personvm);
}
View: check the last column.
#model PersonViewModel
#(Html
.Grid(Model.Persons)
.Build(columns =>
{
columns.Add(model => Html.CheckBox("Check_" + model.Id)).Titled(Html.CheckBox("CheckAll"));
columns.Add().RenderedAs((model, row) => row + 1).Titled("#").Css("text-center");
columns.Add(model => model.Name).Titled("Name");
columns.Add(model => model.Surname).Titled("Surname");
columns.Add(model => model.MaritalStatus).Titled("Marital status");
columns.Add(model => model.Age).Titled("Age");
columns.Add(model => model.Birthday).Titled("Birthday").Formatted("{0:d}");
columns.Add(model => model.IsWorking).Titled("Employed").RenderedAs(model => model.IsWorking == true ? "Employed" : "Unemployed");
columns.Add(model => model.IsSelected).Titled("Selected")
.RenderedAs(model => Model.SelectedName.Contains(model.Name) ?
Html.Raw("<input type='checkbox' name='Input.SelectedAccessRightsIds' value='"+ model.Id + "' checked />")
: Html.Raw("<input type='checkbox' name='Input.SelectedAccessRightsIds' value='" + model.Id + "' />"));
})
)
The output as below:
Reference: MVC6 Grid Formatting
[Note] Before using MVC6 Grid, please make sure you have installed it.

Seed Many-To-Many Database in C# and EF Core

I would like to seed my Database with EF Core and seeding the connecting table for the many-to-many relationship doesn't work.
I've got three models:
public class Droid
{
public int DroidId { get; set; }
public string DroidName { get; set; }
}
public class Colors
{
public int ColorID { get; set; }
public string Color { get; set; }
}
public class DroidColors
{
public int DroidColorID { get; set; }
public int ColorID { get; set; }
public int DroidID { get; set; }
}
And I'm seeding the database right at the beginning. Seeding the droid table and the color table works fine, but the droidcolor table just stays emtpy.
using (var context = new DBContext(serviceProvider.GetRequiredService<DbContextOptions<DBContext>>()))
{
if (context.Colors.Any())
{
return;
}
var colors = new Color[]
{
new Color{Color = "White"},
new Parameter{Color = "Black" },
new Parameter{Color = "Orange"},
};
foreach (Color c in colors)
{
context.Colors.Add(c);
}
context.SaveChanges();
if (context.Droids.Any())
{
return;
}
var droids = new Droid[]
{
new Droid{DroidName = "R2-D2"},
new Droid{DroidName = "C-3PO"},
new Droid{DroidName = "BB-8"},
};
foreach (Droid d in droids)
{
context.Droids.Add(d);
}
context.SaveChanges();
if (context.DroidColors.Any())
{
return;
}
var droidcolors = new DroidColor[]
{
new DroidColor{DroidID = 1, ColorID = 1},
new DroidColor{DroidID = 1, ColorID = 2},
new DroidColor{DroidID = 2, ColorID = 1},
new DroidColor{DroidID = 2, ColorID = 2},
new DroidColor{DroidID = 2, ColorID = 3},
new DroidColor{DroidID = 3, ColorID = 1},
new DroidColor{DroidID = 3, ColorID = 3}
};
foreach (DroidColor DC in droidcolors)
{
context.Droids.Add(DC);
}
context.SaveChanges();
What am I missing? EF Core seems to ignore my third data array, after working with the first and the second as expected.

Xamarin XAML Previewer Design Data Bindings

I am trying to set up a Design Time Data binding in a Xamarin XAML page so I can utilise the previewer to design my page more quickly. I have set up a static class which contains my data, but when I preview it does not show me the bound data.
How do I get the binding to work? I am trying it with the Test property
XAML
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:TechsportiseApp.Data;assembly=DesignTimeData"
BindingContext="{x:Static local:DesignTimeData.ViewModel}"
x:Class="TechsportiseApp.Views.Timer" x:Name="ParentView" Title="Timer">
<Entry Margin = "3" Text="{Binding Test}" />
</ContentPage>
DesignTimeData.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using TechsportiseApp.Models;
namespace TechsportiseApp.Data
{
public class DesignTimeData
{
public static class ViewModelLocator
{
private static TimerViewModel timerVM;
public static TimerViewModel ViewModel => timerVM ?? (timerVM = new TimerViewModel());
public class TimerViewModel
{
public ObservableCollection<Timing> Timings { get; set; } = new ObservableCollection<Timing>
{
new Timing { Position = 1, BatchCode = "A", Elapsed = "01:02:03.001", EndTime = DateTime.Now, StartTime = DateTime.Now, Id = 1, RaceId = 111 }
};
public List<RaceOption> RaceOptions { get; set; } = new List<RaceOption>
{
new RaceOption { Id = 1, RaceId = 2, Colour= "Red", OptionName="5k" },
new RaceOption { Id = 3, RaceId = 4, Colour= "Blue", OptionName="10k" },
new RaceOption { Id = 5, RaceId = 6, Colour= "Green", OptionName="15k" },
new RaceOption { Id = 5, RaceId = 8, Colour= "Yello", OptionName="20k" },
};
public string Test = "Bind Test";
}
}
}
}
public class TimerViewModel
{
private string _test = "Bind Test";
public string Test
{
get
{
return _test;
}
set
{
value = _test;
//implement your INotifyOnPropertyChangedHere...
}
}
/// the rest of your view model code
}
It looks like you have not properly defined your class. Change the below structure
From
namespace TechsportiseApp.Data
{
public class DesignTimeData
{
public static class ViewModelLocator
{
private static TimerViewModel timerVM;
public static TimerViewModel ViewModel => timerVM ?? (timerVM = new TimerViewModel());
public class TimerViewModel
{
public ObservableCollection<Timing> Timings { get; set; } = new ObservableCollection<Timing>
{
new Timing { Position = 1, BatchCode = "A", Elapsed = "01:02:03.001", EndTime = DateTime.Now, StartTime = DateTime.Now, Id = 1, RaceId = 111 }
};
public List<RaceOption> RaceOptions { get; set; } = new List<RaceOption>
{
new RaceOption { Id = 1, RaceId = 2, Colour= "Red", OptionName="5k" },
new RaceOption { Id = 3, RaceId = 4, Colour= "Blue", OptionName="10k" },
new RaceOption { Id = 5, RaceId = 6, Colour= "Green", OptionName="15k" },
new RaceOption { Id = 5, RaceId = 8, Colour= "Yello", OptionName="20k" },
};
public string Test = "Bind Test";
}
}
}
}
To
namespace TechsportiseApp.Data
{
public class DesignTimeData
{
private static TimerViewModel timerVM;
public static TimerViewModel ViewModel => timerVM ?? (timerVM = new TimerViewModel());
public class TimerViewModel
{
public ObservableCollection<Timing> Timings { get; set; } = new ObservableCollection<Timing>
{
new Timing { Position = 1, BatchCode = "A", Elapsed = "01:02:03.001", EndTime = DateTime.Now, StartTime = DateTime.Now, Id = 1, RaceId = 111 }
};
public List<RaceOption> RaceOptions { get; set; } = new List<RaceOption>
{
new RaceOption { Id = 1, RaceId = 2, Colour= "Red", OptionName="5k" },
new RaceOption { Id = 3, RaceId = 4, Colour= "Blue", OptionName="10k" },
new RaceOption { Id = 5, RaceId = 6, Colour= "Green", OptionName="15k" },
new RaceOption { Id = 5, RaceId = 8, Colour= "Yello", OptionName="20k" },
};
public string Test = "Bind Test";
}
}
}
This should resolve your issue

dropdown population with viewmodel asp.net mvc

i am new in MVC. so when see code to understand then some time confusion occur. here i am giving a code. so please see the code first.
public class ProductViewModel
{
public int ID { set;get;}
public string Name { set;get;}
}
public class OrderViewModel
{
private List<ProductViewModel> _products;
public int OrderNumber { set; get; }
public List<ProductViewModel> Products
{
get
{
if (_products == null)
{
_products = new List<ProductViewModel>();
_products.Add(new ProductViewModel { ID = 1, Name = "Ketchup" });
_products.Add(new ProductViewModel { ID = 1, Name = "Mustard" });
_products.Add(new ProductViewModel { ID = 1, Name = "Relish" });
_products.Add(new ProductViewModel { ID = 1, Name = "Mayo" });
}
return _products;
}
}
public int SelectedProductId { set;get;}
}
public ActionResult Order()
{
OrderViewModel orderVM = new OrderViewModel();
return View(orderVM);
}
#model ORderViewModel
#using (Html.BeginForm())
{
<p>
#Html.DropDownListFor(x => x.SelectedProductId , new SelectList(Model.Products, "Value", "Text"), "-- Select Product--")
</p>
}
my question is can i place this code public int SelectedProductId { set;get;} in ProductViewModel instead of OrderViewModel.
if it is possible then what to change in code and in view html ?

How to pass a record to controller in html.actionlink of webgrid

I'm using below webgrid to show user details. When I click on Edit link in grid, the corresponding record should move to controller action method, "EditOfflineUser".
I tried to send item value as shown below. But the value is null in controller
Please let me know how to pass the corresponding record to controller.
In the below code, I'm getting userId value in controller.
CSHtml file
#if (Model.OfflineUserList.Count != 0)
{
WebGrid gridoffline = new WebGrid(rowsPerPage: 10, canPage: true);
gridoffline.Bind(Model.OfflineUserList, autoSortAndPage: true, rowCount: 10);
#gridoffline.GetHtml(
fillEmptyRows: false,
tableStyle: "table",
headerStyle: "header",
alternatingRowStyle: "alt",
htmlAttributes: new { id = "wbgUserOffline" },
mode: WebGridPagerModes.All,
columns: gridoffline.Columns(
gridoffline.Column(columnName: "UserName", header: "Username", canSort: false),
gridoffline.Column(columnName: "FirstName", header: "Firstname", canSort: false),
gridoffline.Column(columnName: "LastName", header: "Lastname", canSort: false),
gridoffline.Column(columnName: "RegistrationOffice", header: "Registration Office", canSort: false),
gridoffline.Column(header: "", format: #<text>#Html.ActionLink("Edit", "EditOfflineUser", "Admin", new { id = item.UserId, offlineUsers = item }, new { id = "btnEditClick", #class = "edit" })</text>),
gridoffline.Column(header: "", format: #<text>#Html.ActionLink("View", "ViewOfflineUser", "Admin", new { usrname = item.UserName }, new { #class = "view" })</text>)));
}
Controller:
public ActionResult EditOfflineUser(int id, ListOfUsers offlineUsers)
{
//getting id value
//offlineUsers is null
}
Model:
public class ListOfUsers
{
public ListOfUsers()
{
OnlineUserList = new List<ListOfUsers>();
OfflineUserList = new List<ListOfUsers>();
}
public List<ListOfUsers> OnlineUserList { get; set; }
public List<ListOfUsers> OfflineUserList { get; set; }
public List<SelectListItem> UserCountryList { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string RegistrationOffice { get; set; }
public string PositionAtOffice { get; set; }
public string PhoneNo { get; set; }
}