In my app, users can login via a barcode scan.
The scan triggers a controller action like so:
function scanner(value) {
var badge = (value.startsWith('B-') || value.startsWith('B-')); //b- of B- = badge scan
if (badge)
{
$.ajax({
type: 'GET',
url: '/Login/Login',
data: {'badge': value},
succes: function () {
console.log("logged in");
}
});
}
else return;
}
Controller action:
public ActionResult Login(string badge)
{
string userName = string.Empty;
if (badge != null)
{
int oncid;
if (Int32.TryParse(badge.Substring(2), out oncid))
{
Core.Employee employee = Data.Oracle.GetEmployee(oncid.ToString());
if (employee != null)
{
userName = employee.FirstName + ' ' + employee.Name;
}
}
else
userName = "invalid badge";
}
ViewBag.UserName = userName;
return PartialView("_Login");
}
in _Layout.cshtml:
<nav class="navbar fixed-top navbar-expand-sm navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="#"><img src="~/Content/Images/logo.png" height="36" width="36" class="d-inline-block align-top"> App Name</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto mt-2 mt-lg-0">
<li class="nav-item active">
#*<a class="nav-link" href="#Url.Action("Index", "Home")">Home <span class="sr-only">(current)</span></a>*#
<a class="nav-link" href="#Url.Action("Index", "Home")"><span class="fas fa-home fa-2x" aria-hidden="true"></span></a>
</li>
<li class="nav-item">
<a class="nav-link" id="smrButton" href="#">SMR</a>
</li>
</ul>
</div>
#Html.Partial("_Login")
</div>
</nav>
_Login.cshtml just has #ViewBag.UserName for now.
If i set a breakpoint here, i can see that ViewBag.UserName holds the correct value, however, nothing is displayed in my page layout. What am i missing here?
Try using Session instead of ViewBag. For example:
Session["username"] = userName;
And call it in the view, simple as that
Related
I have a form with large no:of fields to input data.
The Page also has file upload option like below
Want to download the files without submitting this form and also without refreshing this page. what have done so far is
#if (Model.AttachForms != null)
{
<div class="form-row mt-1">
<div class="col-md-12">
<ul class="list-group">
#foreach (var item in Model.AttachForms)
{
<li class="list-group-item d-flex justify-content-between align-items-center pt-1 pb-1">
#Html.DisplayFor(modelItem => item.Name)
<button class="badge badge-primary badge-pill" value="#item.Name" id="FileDownloadBtn">Download</button>
</li>
}
</ul>
</div>
</div>
}
Javascript Code
$("#FileDownloadBtn").click(function () {
event.preventDefault();
var rootPath = '#Url.Content("~")';
$.ajax({
type: "post",
url: rootPath + "/RequestFormEdit?handler=FileDownload",
data: { filename: this.value },
success: function (data) {
}
})
})
cshtml.cs
public IActionResult OnPostFileDownload(string filename)
{
//string DownloadFileName = filename;
if (filename != null)
{
var Folder = RequestID.ToString();
string fileview = Path.Combine(_env.WebRootPath, "Documents", Folder, filename);
WebClient User = new WebClient();
Byte[] fileBuffer = System.IO.File.ReadAllBytes(fileview);
if (fileBuffer != null)
{
return File(fileBuffer, "application/octet-stream", filename);
}
}
return null;
}
My doubt is how can to pass this file content data as json string and download the file as same as the uploaded format.
Edited
Edited the filedownload button with formdata, but still its not working.
My doubt is i am passing file name in the download button like below
<ul class="list-group">
#foreach (var item in Model.AttachForms)
{
<li class="list-group-item d-flex justify-content-between align-items-center pt-1 pb-1">
#Html.DisplayFor(modelItem => item.Name)
<button class="badge badge-primary badge-pill" value="#item.Name" id="FileDownloadBtn">Download</button>
</li>
}
</ul>
Do i need to give get().files in jquery?
$("#FileDownloadBtn").click(function () {
event.preventDefault();
var formData = new FormData();
var rootPath = '#Url.Content("~")';
var files = $("#FileDownloadBtn").get(0).files;
formData.append('Files', files[0]);
$.ajax({
type: "post",
url: rootPath + "/RequestFormEdit?handler=FileDownload",
data: formData,
processData: false,
contentType: false,
success: function (data) {
}
})
})
This is my backend code to download
public IActionResult FileDownload(string filename)
{
//string DownloadFileName = filename;
if (filename != null)
{
var Folder = RequestFormMaster.RequestID.ToString();
var fileUploadPath = _fileuploadurl;
string fileview = Path.Combine(fileUploadPath, Folder, filename);
WebClient User = new WebClient();
Byte[] fileBuffer = System.IO.File.ReadAllBytes(fileview);
if (fileBuffer != null)
{
return File(fileBuffer, "application/octet-stream", filename);
}
}
return null;
}
FILE UPLOAD
<div class="col-sm-4 mb-2 pl-sm-2" >
<label class="pl-4 pt-2"><b>Upload Attachments</b></label>
<div class="form-row" style="border:3px dashed #D3D3D3;outline-offset:-10px;height:75px;border-radius:5px;">
<div class="col-md-12">
<label for="attachment" style="padding: 15px 145px;">
<a class="btn" style="background-color:#E9ECEF;" role="button" aria-disabled="false">Click here to upload files</a>
</label>
<input id="attachment" style="visibility: hidden; position: absolute; display: block;" type="file" asp-for="ReqSupportingFiles" multiple>
</div>
</div>
#if (Model.AttachForms != null)
{
<div class="form-row mt-1">
<div class="col-md-12">
<ul class="list-group">
#foreach (var item in Model.AttachForms)
{
<li class="list-group-item d-flex justify-content-between align-items-center pt-1 pb-1">
#Html.DisplayFor(modelItem => item.Name)
<button class="badge badge-primary badge-pill" value="#item.Name" id="FileDownloadBtn">Download</button>
</li>
}
</ul>
</div>
</div>
}
<div class="form-row mt-1">
<div class="col-md-12">
<p id="files-area">
<span id="filesList">
<span id="files-names"></span>
</span>
</p>
</div>
</div>
</div>
using default code for Identity in Blazor I have seen that by using authentication cookies the user isn't set as logged, while the cookie exist in the browser and the link/action to be signed out wasn't callled
What could I possibly need to check what would be causing this behavior?
the only line of code I had used is a js code to call automatically the signout action on post which only exist in the logout view(which is only called in the lougout link, but for example calling the login page shows as if it wasnt logged in(which is checked at the loging partial view
<script>
(() =>
{
document.getElementById('logoutFormLocal').submit();
})();
</script>```
#using Microsoft.AspNetCore.Identity
#inject SignInManager<IdentityUser> SignInManager
#inject UserManager<IdentityUser> UserManager
<ul class="navbar-nav">
#if (SignInManager.IsSignedIn(User))
{
<li class="nav-item">
<a id="manage" class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello #UserManager.GetUserName(User)!</a>
</li>
<li class="nav-item">
<form id="logoutForm" class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="#Url.Page("/Index", new { area = "" })">
<button id="logout" type="submit" class="nav-link btn btn-link text-dark">Logout</button>
</form>
</li>
}
else
{
<li class="nav-item">
<a class="nav-link text-dark" id="register" asp-area="Identity" asp-page="/Account/Register">Register</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" id="login" asp-area="Identity" asp-page="/Account/Login">Login</a>
</li>
}
</ul>
I am studying spring boot and making pet project and now I need do pagination and sorting. I am using thymeleaf in html page and I have some problem with Pageable and Sort field.
I have controller
#GetMapping
public String showAllClassrooms(Model model, Pageable page) {
Page<Classroom> classroomPage = classroomService.getAndSort(page);
model.addAttribute("classroomPage", classroomPage);
return "classrooms-page";
}
and Service method
#Transactional
public Page<Classroom> getAndSort(Pageable paging) {
long totalElement = count();
List<Classroom> classrooms = new ArrayList<>();
if (paging.getSort().toString().contains("Address")) {
classrooms = getAndSortByAddress(paging.getPageSize(), (int) paging.getOffset());
} else {
classrooms = getAndSortByCapacity(paging.getPageSize(), (int) paging.getOffset());
}
return new PageImpl<Classroom>(classrooms, paging, totalElement);
}
and naviagion in page
<nav aria-label="..." th:object="${classroomPage}">
<ul class="pagination justify-content-center">
<li class="page-item" th:classappend="*{(getNumber == 0 ? 'disabled' : '' )}">
<a class="page-link" th:href="#{/classrooms/(page=*{getNumber-1}, size = *{size}, sort=*{sort})}">«</a></li>
<li class="page-item" th:classappend="*{(getNumber == getNumber ? 'active' : '' )}">
<a class="page-link" th:text="*{getNumber} + 1" th:href="#{/classrooms/(page=*{getNumber}, sort=*{sort})}" ></a></li>
<li class="page-item" th:classappend="(*{getNumber} == *{getTotalPages}-1 ? 'disabled' : '' )">
<a class="page-link" th:href="#{/classrooms/(page=*{getNumber+1} , size = *{size} , sort=*{sort})}">»</a>
</li>
<li class="page-item">
<form action="#" method="get" th:action="#{/classrooms/}"
>
<div class="input-group">
<input class="w-25 p-1" type="text" name="page" th:value="${classroomPage.getNumber+1}">
<input type="hidden" name="size" th:value="${classroomPage.size}">
<input type="hidden" name="sort" th:value="${classroomPage.getSort}">
<span class="input-group-text" th:utext="${classroomPage.getNumber + 1}" ></span>
</div>
</form>
</li>
</ul>
</nav>
everything is working alright, but I have double direction in address field of browser, like this
http://localhost:8080/classrooms/?page=2&size=5&sort=Capacity:%20ASC:%20ASC:%20ASC:%20ASC:%20ASC:%20ASC:%20ASC:%20ASC
Thank you for you time, and sorry for my bad english :)
I have a view with multiple tabs. Each having different forms. When I submit a form from one tab, it returns to same page but primary tab. How could I get to return to same tab from which I was working.
Controller
public function recieve(Request $request)
{
$item = Item::find($request->input('item'));
$item->recieved_at = now();
$item->recieved_status = "1";
$item -> save();
return redirect('/files/'.$item->file)->with('success','Item Recieved Confirmed');
}
view - tabs
<ul class="nav nav-tabs" id="fileTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="profile-tab" data-toggle="tab" href="#profile" role="tab"
aria-controls="profile" aria-selected="true">Profile</a>
</li>
<li class="nav-item">
<a class="nav-link" id="job-tab" data-toggle="tab" href="#job" role="tab" aria-controls="job"
aria-selected="false">Job</a>
</li>
<li class="nav-item">
<a class="nav-link" id="items-tab" data-toggle="tab" href="#items" role="tab" aria-controls="items"
aria-selected="false">Items</a>
</li>
<li class="nav-item"><a class="nav-link" id="mechanic-tab" data-toggle="tab" href="#mechanic" role="tab"
aria-controls="mechanic" aria-selected="false">Labour Hours</a>
</li>
<li class="nav-item">
<a class="nav-link" id="accounts-tab" data-toggle="tab" href="#accounts" role="tab"
aria-controls="accounts" aria-selected="false">Accounts</a>
</li>
<li class="nav-item">
<a class="nav-link" id="accounts-tab" data-toggle="tab" href="#preview" role="tab"
aria-controls="accounts" aria-selected="false">Print Preview</a>
</li>
</ul>
Form
#if($file->job_status == "Closed")#else
{!! Form::open(['action' => 'FilesController#item','method' => 'POST']) !!}
<div class="row pt-3 pb-1">
<div class="form-group col-xs-12 col-sm-12 col-md-2">
{{Form::text('part_number','',['class'=>'form-control','placeholder'=>'Part Number'])}}
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-6">
{{Form::text('description','',['class'=>'form-control','placeholder'=>'Part Name'])}}
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-2">
{{Form::text('qty','',['class'=>'form-control','placeholder'=>'Qty'])}}
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-2">
{{Form::select('recieved_by',$users,null,['class'=>'form-control'])}}
</div>
</div>
{{Form::hidden('file',$file->id)}}
{{Form::submit('Release Item',['class'=>'form-control btn-danger btn btn-sm'])}}
{!! Form::close() !!}
#endif
I tried using hashtag tab name in return redirect statement,
return redirect('/files/'.$item->file."#items-tab")->with('success','Item Recieved Confirmed');
it would simply highlight the name but would not select. How could I achieve it?
your tab navigation,
<ul class="nav nav-tabs" id="tabMenu" role="tablist">
<li><i class="fa fa-camera" aria-hidden="true"></i> Galleries</li>
</ul>
hidden input field for tab
<input type="hidden" name="tab" value="Galleries">
RedirectRoute
$tab = $request->get('tab');
return back()->withInput(['tab'=>$tab]);
Javascript,
<script>
//redirect to specific tab
$(document).ready(function () {
$('#tabMenu a[href="#{{ old('tab') }}"]').tab('show')
});
</script>
If you want to do it in laravel than all you can do is,
-Give an id to each tab and an write an active class.
-Put a hidden input with value of the parent tab id.
-So, laravel will receive the tab id in the request object.
-Now, you can do whatever and return the tab id with to the view.
-Give a if condition to each tab item and check if matches the id from laravel response.
The match the id set the active class to it.
example
<ul>
<li id='tab1 {{ session()->get('tabId') === 'tab1' ? 'active' : '' }}'></li>
<li id='tab2 {{ session()->get('tabId') === 'tab2' ? 'active' : '' }}'></li>
</ul>
// tab1 body
<form>
<input type="hidden" name="tabId" value="tab1">
...
</form>
// tab2 body
<form>
<input type="hidden" name="tabId" value="tab2">
...
</form>
// controller
public funciton(Request $request) {
//tabId
$tabId = $request->input('tabId')
....
....
return redirect()->back()->with('tabId' => $tabId);
}
You can do this:
Controller:
public function tab() {
$active_tab = "tab2";
return view('tabs.index', compact('active_tab'));
}
View:
<ul class="nav nav-tabs">
<li class="#if($active_tab=="tab1") active #endif"><a data-toggle="tab" href="#home">Home</a></li>
<li class="#if($active_tab=="tab2") active #endif"><a data-toggle="tab" href="#menu1">Menu 1</a></li>
<li class="#if($active_tab=="tab3") active #endif"><a data-toggle="tab" href="#menu2">Menu 2</a></li>
</ul>
<div class="tab-content">
<div id="home" class="tab-pane fade #if($active_tab=="tab1") in active #endif">
<h3>HOME</h3>
<p>Some content.</p>
</div>
<div id="menu1" class="tab-pane fade #if($active_tab=="tab2") in active #endif">
<h3>Menu 1</h3>
<p>Some content in menu 1.</p>
</div>
<div id="menu2" class="tab-pane fade #if($active_tab=="tab3") in active #endif">
<h3>Menu 2</h3>
<p>Some content in menu 2.</p>
</div>
</div>
You can show a specific tab with this code:
function showTab(tab){
$('.nav-tabs a[href="#' + tab + '"]').tab('show');
};
// Verify location.hash
if (window.location.hash !== ''){
showTab(window.location.hash);
}
But I would pass a query string in the return, just to make sure there will be no collision with other eventual hashes. Something like:
return redirect('/files/'.$item->file."?openTab=your-tab-id")->with('success','Item Recieved Confirmed');
Of course, you would change the "location.hash" verification to a query string verification. Example: https://davidwalsh.name/query-string-javascript
i have database notification, and i was trying to redirect the user whenever they click one of the notification link it will go to the exact POST id,then mark as read that particular notification being selected. but i couldn't make it work
Here is my controller
public function readbyid($id){
if(isset($notification->data['id'])){
return redirect()->action(
'PostController#show', ['id' => $notification->data['id']]
);
}else{
return redirect()->back();
}
}
Notification Model
public function toArray($notifiable)
{
return [
'id' => $this->post->id,
];
}
Blade View:
<li class="nav-item dropdown"> <a id="messages" rel="nofollow" data-target="#" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="nav-link"><i class="fa fa-bell"></i>#if (auth()->user()->unreadnotifications->count())<span class="badge badge-warning">{{auth()->user()->unreadnotifications->count()}}</span>#endif</a>
<ul aria-labelledby="notifications" class="dropdown-menu">
<li><a rel="nofollow" href="{{Url('markread')}}" class="dropdown-item all-notifications text-center"> <strong> <i class="fa fa-bell"></i>Mark all as Read</strong></a></li>
#foreach(auth()->user()->unreadnotifications as $notify)
<li><a rel="nofollow" href="{{Url('markread/{id}')}}" class="dropdown-item d-flex">
<div class="msg-body">
<h3 class="h5">{{$notify->data['title']}}</h3>
</div> </a></li>#endforeach
</ul>
</li>
Route:
Route::get('markread/{id}', 'NotifyController#readbyid' );