Implement search from inside layout in asp.net core mvc - asp.net-core-mvc

I'm creating my first web app using asp.net core mvc, so I'm stuck with implementing global search using textbox inside layout, I can't find where to implement the search after user press Enter, Is it implemented in controller or something else, and how to implement it...

I'm stuck with implementing global search using textbox inside layout, I can't find where to implement the search after user press Enter
To implement the above requirement, you can refer to the following code snippet.
Adding form with input for searching functionality in _Layout.cshtml
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
<li class="nav-item">
<form id="f_search" method="get" asp-action="Search">
<div class="form-group">
<div class="input-group">
<input id="ipt_search" type="search" class="form-control" name="SearchTerm" />
<span class="input-group-btn">
<button class="btn btn-default">
Search
</button>
</span>
</div>
</div>
</form>
</li>
</ul>
</div>
JS code of checking keydown event and user input
<script>
$(function () {
$('#f_search input').keydown(function (e) {
var searchTerm = $("#ipt_search").val();
if (searchTerm == "" && event.keyCode === 13) {
e.preventDefault();
return false;
}
});
})
</script>
Action method of Search
public IActionResult Search(string SearchTerm)
{
//...
//do query based on SearchTerm
//code logic here
//...
return View();
}
Test Result

Related

SignInManager.IsSignedIn(User) returns false on identity scaffolding

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>

Laravel submit form from a tab and return to same tab in view

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

Ajax not triggering for Partial view

I am adding Partial view in to my main view , the partial view code snippet is:
<li class="item-#j deeper parent active">
<a class="" href="">
<span data-toggle="collapse" data-parent="#menu-group-1" href="#sub-item-#j" class="sign"><i class="icon-plus icon-white"></i></span>
<span class="lbl">Brands</span>
</a>
<ul class="children nav-child unstyled small collapse" id="sub-item-#j">
#foreach (var brand in Model.BrandList)
{
<li class="item-#j deeper parent active">
<div class="checkbox">
<label>
<input type="checkbox" value="#brand._id">
#*<a class="" href="#Url.Action("FilterData", "ShopWindow", new {shopKey=house._id,houseKey=house._id,houseName = house.House})">*#
<span class="lbl">#brand.Brand</span>
#*</a>*#
</label>
</div>
</li>
j++;
}
</ul>
</li>
in my main view I have a script to get all the check boxes that user have selected, the script snippet :
<script type="text/javascript">
var selectedBrand=[];
$("input[type='checkbox']").change(function () {
$('#brand input:checked').each(function () {
selectedBrand.push($(this).attr('value'));
alert("Test");
})
sendAjaxRequest();
});
When I select any check box from the partial view the script's change function is not getting triggered. This change function triggers if I check any checkbox in the main page but not for checkboxes belongs to partial view .
Any idea?
Thanks
I found the solution :
changed
$("input[type='checkbox']").change(function () {
to
$(document).on('change', '.checkbox', function() {

How can i jump one cshtml page to another cshtml?

I have two .cshmtl pages used for registration. When user completes first registration page I want the controller to jump to another cshtml page without going to controller. How can I complete this task?
<div class="control-group form-actions pull-right">
<a href="~/Views/Registration/RegStep2" class="btn btn-primary">
Continue
<i class="fa fa-arrow-circle-right"></i>
</a>
</div>
When user click above continue button he will jump on another controller without controller...
Please see the below method using Partial views.
<div class="control-group form-actions pull-right">
<div id="first-div">
#Html.Partial("PartialView1")
</div>
<div id="second-div" style="display:none;">
#Html.Partial("PartialView2")
</div>
<a href="#" class="btn btn-primary" onclick="onclickContinue">
Continue
<i class="fa fa-arrow-circle-right"></i>
</a>
</div>
<script type="text/javascript">
function onclickContinue(e) {
$("#first-div").hide();
$("#second-div").show();
}
</script>

How to fill an empty <div> with a partial view using ajax

I am using Visual Studio 2013, .Net 4.5, MVC and Visual Basic. I am trying to render a partial view in an empty div of another view using jQuery and Ajax. My script is running successfully in that on the drop down list change, my partial view is rendered, but instead of it rendering in a div on the same view, it renders on it's own page.
Main View:
<div class="col-md-8">
<div class="btn-group">
<button class="btn btn-default dropdown-toggle btn-sm" type="button" id="dropDownSelectBuilding" data-toggle="dropdown"
aria-expanded="true">
<span class="selection"></span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labeledby="dropDownSelectBuilding">
#For Each item In Model
Dim currentItem = item
#<li role="presentation"><a role="menuitem" tabindex="-1" href="/LocationSelect/SelectFloor"
>#Html.DisplayFor(Function(modelItem) currentItem)</a></li>
Next
</ul>
</div>
#section Scripts
<script>
$('#dropDownSelectBuilding').onChange(function () {
$.ajax({
url: '/LocationSelect/SelectFloor',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html'
})
.success(function (result) {
$('#showFloors').html(result);
})
.error(function (xhr, status) {
alert(status);
})
});
</script>
End Section
</div>
</div>
<div class="row" id="showFloors">
</div>
Partial View:
<div class="col-md-4">
<label>*Select the floor this item will move to:</label>
</div>
<div class="col-md-8">
<div class="btn-group">
<button class="btn btn-default dropdown-toggle btn-sm" type="button" id="dropDownSelectFloorMoveTo" data-toggle="dropdown" aria-expanded="true">
<span class="selection"></span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labeledby="dropDownSelectFloorMoveTo">
#For Each item In Model
Dim currentItem = item
#<li role="presentation"><a role="menuitem" tabindex="-1" href="/LocationSelect/SelectFloor"
>#Html.DisplayFor(Function(modelItem) currentItem)</a>
</li>
Next
</ul>
</div>
</div>
Controller:
Public Class LocationSelectController
Inherits Controller
Private db As New MCSCInventoryModels
' GET: LocationSelect
Function Index() As ActionResult
Dim distinctBuildings = From Row In db.tblLocations
Select Row.Building
Distinct
Return View(distinctBuildings)
End Function
' GET: FloorS
Function SelectFloor(ByVal selectedBuilding As String) As PartialViewResult
Dim floorsInSelectedBuilding = From Row In db.tblLocations
Where Row.Building = selectedBuilding
Select Row.Floor
Distinct
Return PartialView(floorsInSelectedBuilding)
End Function
End Class
Can you tell me why this ajax call opens the partial view in it's own page, instead of rendering it in the specified div?
Update I have checked the accepted answers to both of these questions and they have not solved the issue.
Here
and
Here
You are most likely missing the unobtrusive script in your layout page.
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
refer to this question:
Why does Partial View show as full page in MVC 5 Visual Studio 13?
one more thing is to add the last (UnobtrusiveJavaScriptEnabled) line to your config file (Web.Config):
<configuration>
<appSettings>
<add key="webpages:Version" value="2.0.0.0"/>
<add key="webpages:Enabled" value="false"/>
<add key="PreserveLoginUrl" value="true"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
Ultimately what was causing this issue was my use of a non-traditional drop down. To solve the problem I added a class to the <a role="menuitem"> like so:
#<li role="presentation"><a class="ddlist" role="menuitem" tabindex="-1" href="#"
>#Html.DisplayFor(Function(modelItem) currentItem)</a></li>
and then used:
$('.ddlist').click(function () {
to trigger the ajax call.
I also removed the href="/LocationSelect/SelectFloor" which was left over from the design phase and causing the partial view to open in it's own page when a selection was made and the ajax wasn't being triggered.

Resources