How to highlight selected list item in blazor? - css

I have created a simple list in a razor component.it is a simple HTML list with foreach loop.
<ul>
#foreach (var itm in matchingLocations)
{
<li>
<div class="d-flex">
<div class="py-2 pr-2">
<i class="fas fa-map-marker-alt text-glow-1"></i>
</div>
<div class="py-2"><span class="sub-title-2">#itm.CodeName</span></div>
</div>
</li>
}
</ul>
Now I have needed to add the following 2 features to the list
when click on one list item, it should be highlighted.
if we want to click on another item,while one item is already highlighted, the currently highlighted item should be unhighlighted
and clicked item should be highlighted.
. how can I do this using blazor? anybody who knows about this, please help me.

There are many ways to do this. Here's a demo page showing one:
#page "/"
#foreach (var item in Countries)
{
<div class="#DivCss(item) p-2" #onclick="() => SetSelect(item)">
#item.Name
</div>
}
#code {
List<Country> Countries = new List<Country>
{
new Country { Name = "Australia"},
new Country { Name = "Spain"},
new Country { Name = "Croatia"}
};
List<Country> SelectedCountries = new List<Country>();
class Country
{
public string Name { get; set; }
}
bool IsSelected(Country country)
=> SelectedCountries.Any(item => item == country);
string DivCss(Country country)
=> IsSelected(country) ? "bg-success text-white" : "bg-light";
void SetSelect(Country country)
{
if (IsSelected(country))
SelectedCountries.Remove(country);
else
SelectedCountries.Add(country);
}
}

Related

Object reference not set to an instance of an object in line of Layout in View

I am gonna be crazy about this error!
I have a very simple View, without any model or..., and I receive null error in the line of defining Layout, while in the other pages layout works correctly, any idea please?
part of My View:
#{
ViewBag.Title = "رزرو";
Layout = "~/Views/Shared/_Layout.cshtml"; //Error is here
}
and Controller:
public ActionResult Reserves()
{
ViewBag.reservelist = "";
try
{
ViewBag.UnreadMessages = UnreadMessages(Session["PersonId"].ToString());
Guid DoctorId = Guid.Parse(Session["PersonId"].ToString());
List<Reserve> reservelist = db.Reserves.Where(r => r.DoctorId == DoctorId && r.Accepted
== null).ToList();
ViewBag.reservelist = reservelist;
}
catch
{
}
return View();
}
I realized what was the problem!
there was a Session in one of the menu that its value was null and stupid VS couldn't find the problem,
<li>
//The below session was null
<a href="#Url.Action("Chat","Home", new { PId = Session["PId"].ToString() })">
<i class="fas fa-comments"></i>
<span>پیام‌ها</span>
<small class="unread-msg">#ViewBag.UnreadMessages</small>
</a>
</li>

Selecting user with asp.net mvc

I have a list of users and if you click on a user there has to be create a new message.
But every time I click on a user id is 0
I have this:
action method:
public ActionResult StuurBericht(int id = 0, string onderwerp = "")
{
using (var rep = new GebruikerRepository(Context.Klant.Id))
{
var model = PersoneelsDossierService.GetPersoneelsDossierMutatieModel(Context.Klant.Id, GetMutatieRol(), int.Parse(Context.Gebruiker.ExternId), Gebruiker.DienstverbandId, Gebruiker.DienstverbandId, "Functionarissen");
model.Functionarissen = PersoneelsDossierService.GetFunctionarissen(Context.Klant.Id, Gebruiker.DienstverbandId);
BeveiligingService.ControleerGebruikerVanKlant(Context.Klant.Id, Context.Gebruiker.Id);
if (id > 0)
{
ModelState.Clear();
var modelMessage = new Message();
modelMessage.GebruikerId = id;
modelMessage.Onderwerp = string.Format("RE: {0}", onderwerp);
return View(model);
}
}
return View();
}
and this is the view:
#model List<SDB.Models.Stamtabel>
#{
var ItemsByAccordatieFunctieGroep = Model.GroupBy(a => a.Code);
<div class="row">
#foreach (var Accordeerders in ItemsByAccordatieFunctieGroep)
{
<div class="col-md-4">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading blue">#Accordeerders.Key</div>
<!-- List group -->
<ul class="list-group">
#foreach (var Accordeerder in Accordeerders)
{
<li class="list-group-item">
#Accordeerder.Omschrijving
</li>
}
</ul>
</div>
</div>
}
</div>
}
So my question is:
How to return the correct user and that you will get the correct id?
Thank you
this has to be the link for new message:
SelfService/Profiel/Nieuw?id=6240&onderwerp=test
So the controller is: Profiel.
But now the link is this:
/PersoneelsDossier/StuurBericht/0?onderwerp=HRM%20Management
So the controller link is incorrect.
Your #Url.Action is wrong, it should be:
#Accordeerder.Omschrijving

How to bind span value to model in Asp.Net

I have a form where I need to use to buttons(plus and minus) to set count, but I can't figure out how can I bind this counter to model.
I have model looks like:
public class Order
{
public string Name {get; se;}
public int Count {get; set;}
}
Also I have view with form looks like:
#model SushiJazz.Models.ViewModels.OrderViewModel
<div class="container">
#using (Html.BeginForm("CreateOrder", "Order", FormMethod.Post, new { #class = "basket-form" }))
{
<div class="basket-form__input-line">
<label for="b-name" class="basket-form__label">
Name <span class="star-req">*</span>
</label>
#Html.TextBoxFor(model=>model.Name, new { #class="basket-form__input", #id="b-name", #type="tel", #autofocus="autofocus"})
</div>
<div class="basket-counter order-counter static">
<span class="add-del-btn blue">-</span>
<span class="basket-counter-number">2</span>
<span class="add-del-btn blue">+</span>
</div>
}
</div>
So, How can I bind my basket-counter to Model.Count property?
Is it posible?
<span>#Model.Name</span>
And hide the texbox data like this:
#Html.HiddenFor(m => m.Name, new { #readonly = "readonly", #class = "form-control" })
Try this, I have used this in my project and it is working fine.

Display same data again and again in asp.net mvc

This is my LINQ code:
public JsonResult getfull()
{
var coursename = Session["course"].ToString();
var location = Session["location"].ToString();
var result = (from insti in db.Institute_Master
join course in db.Course_Detail on insti.InstituteId equals course.InstituteId
join coursemaster in db.Course_Master on course.CourseId equals coursemaster.CourseId
join facility in db.Facility_Detail on insti.InstituteId equals facility.InstituteId
join masterfacility in db.Facility_Master on facility.FacilityMasterID equals masterfacility.FacilityMasterId
where coursemaster.CourseName == coursename || insti.City == location
select new
{
//Id = insti.InstituteId,
name = insti.InstituteName,
university = insti.University,
Contact = insti.ContactNo,
address = insti.Address,
email = insti.EmailId,
zipcode = insti.Zipcode,
country = insti.Country,
state = insti.State,
city = insti.City,
start = insti.EstablishOn,
image = insti.ProfilePhoto,
fees = course.TotalFees,
mode = course.Mode,
coursename = coursemaster.CourseName,
duaration = coursemaster.duration,
discription = coursemaster.Discription,
eligibility = coursemaster.Eligibility,
recognization = coursemaster.Recognization,
facility = masterfacility.FacilityName
}).Distinct();
ViewBag.facilies = list;
return Json(result, JsonRequestBehavior.AllowGet);
}
This method is return json result which is handled by angular js and I mention angularjs code below.
I am using AngularJs To display a data and my record is repeating for particular facility.
This is my tables:
This is a problem that display same record again for his facility:
This is my Angularjs code
<h1>Show Institute</h1>
<div data-ng-app="myModule">
<div data-ng-controller="myController">
<ul class="w3-ul w3-card-4" data-ng-repeat="detail in employees">
<li class="w3-padding-16 institute-list">
<span class="w3-xlarge">{{detail.name | uppercase}}</span>,<span>{{detail.address}}</span><br>
<img alt="image" src="~/images/{{detail.image}}" class="w3-left w3-margin-right img-institute-list" style="width:60px" />
<span class="w3-xlarge">{{detail.coursename | uppercase}}</span>,<span>Course Duration {{detail.duaration}}</span>,<span>Course Mode {{detail.mode}}</span>,<span>{{detail.discription}}</span><br>
<span><b>Fees : </b>INR {{detail.fees}}</span><br>
<span><b>{{detail.recognization | uppercase}}</b> Recognised</span><br>
<span>Facility {{detail.facility}}</span>
<button class="w3-btn w3-blue" id="detail">More Details</button>
</li>
<script>
$(document).ready(function () {
$("button").click(function () {
$("#moredetail").toggle();
});
});
</script>
<li class="w3-padding-16 institute-list" id="moredetail" style="display:none">
<span class="w3-xlarge">{{detail.contact}}</span> <span class="w3-xlarge">{{detail.email}}</span><br />
<span class="w3-xlarge" >{{detail.zipcode}}</span> <span class="w3-xlarge" >{{detail.country}}</span> <br/>
<span class="w3-xlarge" >{{detail.state}}</span> <span class="w3-xlarge" >{{detail.city}}</span> <br />
<span class="w3-xlarge" >{{detail.start}}</span>,
</li>
</ul>
</div>
</div>
<script>
var app = angular
.module("myModule", [])
.controller("myController", function ($scope, $http) {
$http.get("/home/getfull")
.then(function (response) {
$scope.employees = response.data;
});
})
</script>
</div>
</body>
</html>
This code is for displaying data in a view view json method
Can anyone help me in this?
It keeps adding the same record because you have "select new". What you need is model like:
public class CourseModel
{
public int InstituteId {get; set;}
public string InstituteName {get; set;}
public string University {get; set;}
ETC...
}
Then in your MVC Controller:
var result = (from insti in db.Institute_Master
join course in db.Course_Detail on insti.InstituteId equals course.InstituteId
join coursemaster in db.Course_Master on course.CourseId equals coursemaster.CourseId
join facility in db.Facility_Detail on insti.InstituteId equals facility.InstituteId
join masterfacility in db.Facility_Master on facility.FacilityMasterID equals masterfacility.FacilityMasterId
where coursemaster.CourseName == coursename || insti.City == location
var courses = new List<CourseModel>();
foreach(var c in result)
{
courses.Add(new CourseModel
{
InstitueName = insti.InstituteName,
University = insti.University,
ETC...
});
}
return Json(courses, JsonRequestBehavior.AllowGet;
}
I hope this helps!

Menu in Site Master in MVC. How to highlight selected page [duplicate]

I need to highlight active link in the menu. My menu is in the master page by the way. I'm looking for the best way to implement this? Any ideas?
The best way to handle this is to write an HTML helper. You could use RouteData.Values["action"] to get the currently executing action and compare to the menu name and if they match apply a CSS class that will highlight it.
public static MvcHtmlString MenuItem(
this HtmlHelper htmlHelper,
string action,
string text
)
{
var menu = new TagBuilder("div");
var currentAction = (string)htmlHelper.ViewContext.RouteData.Values["action"];
if (string.Equals(
currentAction,
action,
StringComparison.CurrentCultureIgnoreCase)
)
{
menu.AddCssClass("highlight");
}
menu.SetInnerText(text);
return MvcHtmlString.Create(menu.ToString());
}
And then use this helper to render the menu items:
<%: Html.MenuItem("about", "About us") %>
<%: Html.MenuItem("contact", "Contact us") %>
...
I am always using this solution
Html Part
<ul>
#Html.ListItemAction("Home Page","Index","Home")
#Html.ListItemAction("Manage","Index","Home")
</ul>
Helper Part
public static class ActiveLinkHelper
{
public static MvcHtmlString ListItemAction(this HtmlHelper helper, string name, string actionName, string controllerName)
{
var currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
var currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
var sb = new StringBuilder();
sb.AppendFormat("<li{0}", (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) &&
currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase)
? " class=\"active\">" : ">"));
var url = new UrlHelper(HttpContext.Current.Request.RequestContext);
sb.AppendFormat("{1}", url.Action(actionName, controllerName), name);
sb.Append("</li>");
return new MvcHtmlString(sb.ToString());
}
}
I use this solution:
First - add attribute data-menuPageId to your menu links
<ul class="menu">
<li data-menuPageId="home">
#(Html.Link<HomeController>(x => x.Index(), "Home"))
</li>
<li data-menuPageId="products">
#(Html.Link<ProductsController>(x => x.Index(), "Products"))
</li>
</li>
Next - add hidden field for current page Id to Layout.cshtml
<input type="hidden" id="currentPageId" value="#(ViewBag.Page ?? "home")" />
Add ViewBag.Page initializtion at your pages like Home or Products
#{
ViewBag.Page = "products";
}
And last thing you should reference this javascipt from yor Layout.cshtml
$(function() {
var pageIdAttr = "data-menuPageId";
var currentPage = $("#currentPageId").attr("value");
var menu = $(".menu");
$("a[" + pageIdAttr + "]").removeClass("selected");
$("a[" + pageIdAttr + "=\"" + currentPage + "\"]", menu).addClass("selected");
});
In layout try like following:
#{
string url = Request.RawUrl;
}
#switch (url)
{
case "/home/":
#Html.ActionLink("Home", "../home/", null, new { #style = "background:#00bff3;" })
#Html.ActionLink("Members", "../home/MembersList/")
break;
case "/home/MembersList/":
#Html.ActionLink("Home", "../home/")
#Html.ActionLink("Members", "../home/MembersList/", null, new { #style = "background:#00bff3;" })
break;
default:
#Html.ActionLink("Home", "../home/")
#Html.ActionLink("Members", "../home/MembersList/")
break;
}
The simplest solution:
1) Connect jQuery to #RenderBody ()
2) On Layout
...
<li class="nav-item">
<a class="nav-link text-dark" id="navItemPortfolio" asp-area="" asp-controller="Home" asp-action="Portfolio">Portfolio</a>
</li>
...
3) Write something similar on your page (View)
<script>
$(function () {
$("#navItemPortfolio").addClass("active");
});
</script>
I'm pretty sure you can do this with pure CSS. It involves class selectors and faffing around with the body tag. I would go with the helper method every day of the week.

Resources