I can't catch the JavaScript keyup event of the Input element and call Search method in the HomeController. Net Core 6.

Volk Volk 301 Reputation points
2022-09-08T13:49:52.887+00:00

Hi!

I have a search bar SearchInput.

<header>  
  
<ul>  
			<li class="search">  
				<a class="fa-search" href="#search">Search</a>  
				<form id="search" method="get" action="#">  
					<input id="SearchInput" type="text" name="query" placeholder="@language.Getkey("search")"/>  
				</form>  
			</li>  
  
		</ul>  
  
</header>  

239115-searchpanel.png

What I just didn't do to catch this event and redirect it to the controller.
But I can't even call keyup in javascript - the function just isn't called.

Here are some examples:

@section Scripts{  
  
	<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"/>  
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"/>  
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"/>  
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>  
  
	<script type="text/javascript">	  
  
		let filterInput = document.getElementById('SearchInput');  
		filterInput.addEventListener('keyup', filterNames);  
  
		function filterNames() {  
			alert(@Model);  
		}  
  
	</script>  
  
	<script type="text/javascript">  
  
		// JS+ASP Net Core Get data from controller  
		// https://stackoverflow.com/questions/69210262/jsasp-net-core-get-data-from-controller  
  
		$("#SearchInput").keyup(  
  
			var searchText = $("#SearchInput").val().toLowerCase();  
  
			alert(@Model);  
  
			return;  
  
			$.ajax({  
				url: "~/Customer/Home/Search",  
				type: "GET",  
				data: { text: searchText },  
				success: function (res) {  
					$("#convertnum").html(res);  
				},  
				error: function (hata, ajaxoptions, throwerror) {  
					$("#convertnum").html("convert failed");  
				}  
			});  
		);  
  
	</script>  
  
	<script type="text/javascript">  
  
		$(document).ready(function () {  
  
			$("#SearchInput").keyup(  
  
				function() {  
  
					// ASP .Net Core Call Controller Function from Javascript with redirect from Controller  
					// https://stackoverflow.com/questions/70331625/asp-net-core-call-controller-function-from-javascript-with-redirect-from-contro  
  
					var searchText = $("#SearchInput").val().toLowerCase();  
  
					window.location.href ="~/Customer/Home/Search";  
					//window.location.href ="Controller/Function?Search";  
				}  
			);  
        });  
  
	</script>  
}  

How do I realize it and just call public IActionResult Search(string text) { } in HomeController (Areas\Customer\Controllers\HomeController.cs)?

Thanks!

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
3,540 questions
0 comments No comments
{count} votes

5 answers

Sort by: Most helpful
  1. Michael Taylor 41,756 Reputation points
    2022-09-08T14:55:17.95+00:00

    Your HTML is malformed (your GetKey function call is using double quotes inside double quotes). That is causing issues potentially but since you're using Razor I haven't tested it. Your initial function is trying to hook up the event before the element is even defined so that would fail as well. The browser's console window should be showing you errors for these.

    Here's the simplest equivalent code to do what you want.

       <!DOCTYPE html>  
       <html>  
         
       <head>  
           <title>Test</title>  
           <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>  
         
           <script type="text/javascript">  
               $(document).ready(function () {  
                   $("#SearchInput").keyup(function (event) {  
                       var searchText = event.target.value.toLowerCase();  
                       console.log(searchText);  
                   })  
               })  
           </script>  
       </head>  
         
       <body>  
           <ul>  
               <li class="search">  
                   <a class="fa-search" href="#search">Search</a>  
                   <form id="search" method="get" action="#">  
                       <input id="SearchInput" type="text" name="query" placeholder='@language.Getkey(" search")' />  
                   </form>  
               </li>  
           </ul>  
       </body>  
         
       </html>  
    
    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 43,901 Reputation points
    2022-09-09T16:16:21.433+00:00

    Also the url in the ajax call does not support ~/. You need to use razor syntax to generate, or the best sotionis to set the base href in html

    1 person found this answer helpful.

  3. Volk Volk 301 Reputation points
    2022-09-09T15:36:18.88+00:00

    I put the code in the layout as you said - the result is the same. Here there is a template that I use. It has a menu at the top with a search. future-imperfect As a result, my layout works well everywhere and as it should. You can download the template Future Imperfect and look inside index.html. I have some differences in my layout. The main code in _Layout.cshtml page contains all the other parts of the code. I attach, in particular, _Layout.cshtml and HeaderParties.shtml - this is what concerns this problem.

    _Layout.cshtml

    <!DOCTYPE html>  
    <html lang="en">      
    <head>  
      
        <!-- Meta -->  
        @await Html.PartialAsync("MetatagsPartial")      
      
        <!-- Css -->  
        @await Html.PartialAsync("CssPartial")  
      
    </head>      
        <body class="is-preload">  
      
                 <!-- Wrapper -->  
     <div id="wrapper">  
      
                <!-- Header -->  
                @await Html.PartialAsync("HeaderPartial") <!-- ----- !!! ----- -->  
      
                <!-- Menu -->  
                @await Html.PartialAsync("MenuPartial")  
      
                <!-- Main -->  
                <div class="container">  
                    <main role="main" class="pb-3">  
                        @RenderBody()  
                    </main>  
                </div>  
      
                <!-- Scripts -->              
                @await Html.PartialAsync("ScriptsPartial")  
                @await RenderSectionAsync("Scripts", required: false)  
      
            </div>      
        </body>      
    </html>  
    

    HeaderPartial.cshtml

    @using Microsoft.AspNetCore.Http  
    @using Microsoft.AspNetCore.Http.Extensions;  
    @using System.Globalization  
      
    @inject LanguageService language  
      
    <!-- Header -->  
    <header id="header">  
      
        <h1><a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Future Imperfect</a></h1>  
      
        <nav class="links">  
            <ul>  
      
                <li><a asp-area="Customer" asp-controller="Home" asp-action="Catalog">@language.Getkey("catalog")</a></li>  
                <li><a asp-area="Customer" asp-controller="Home" asp-action="Portfolio">@language.Getkey("portfolio")</a></li>  
                <li><a asp-area="Customer" asp-controller="Home" asp-action="Contact">@language.Getkey("contacts")</a></li>  
      
                <partial name="_LoginPartial" />  
      
            </ul>  
        </nav>      
      
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>  
      
        <script type="text/javascript">  
      
     $(document).ready(  
      
     function () {  
      
     $("#SearchInput").keyup(  
      
     function(event) {  
      
     var searchText = $("#SearchInput").val().toLowerCase();  
      
     alert(@Model);  
      
     //window.location.href ="Controller/Search?text=" + searchText;  
      
     $.ajax({  
     url: "~/Areas/Customer/Home/Search",  
     type: "GET",  
     data: { text: searchText },  
     success: function (res) {  
     $("#convertnum").html(res);  
     },  
     error: function (hata, ajaxoptions, throwerror) {  
     $("#convertnum").html("convert failed");  
     }  
     });  
     }  
     );  
     });  
      
        </script>  
      
        <nav class="main">  
      
            <ul>  
                <li class="search">  
                    <a class="fa-search" href="#search">Search</a>  
                    <form id="search" method="get" action="#">  
                        <input id="SearchInput" type="text" name="query" placeholder='@language.Getkey("search")' />  
                    </form>  
                </li>  
      
                <li class="menu">  
                    <a class="fa-bars" href="#menu">Menu</a>  
                </li>  
            </ul>  
        </nav>  
      
    </header>  
    

  4. Volk Volk 301 Reputation points
    2022-09-09T17:45:42.927+00:00

    This option works almost correctly in my layout. :)
    This example helped: asp-net-core-call-controller-method-in-javascript-without-ajax

    But this reloads the whole page (when entering any character) so the Search field will always be empty. I'm thinking of using the Enter key if I can't reload the @RenderBody() separately.

    window.location.href = '@Url.Action("Search", "Home")' + '?text=' + searchText;  
    

    This also works, I go to the HomeController-->Search method, but the page does not react in any way and does not even reload, the transition to the Search.cshtml page does not occur. But I would like the @RenderBody() to show the Search.html page, and the upper header to remain as it is.

    $.ajax({  
     url: "Customer/Home/Search",  
     type: "GET",  
     data: { text: searchText },  
     success: function (res) {  
     $("#convertnum").html(res);  
     },  
     error: function (hata, ajaxoptions, throwerror) {  
     $("#convertnum").html("convert failed");  
     }  
     });  
    
    
    public IActionResult Search(string text)  
            {  
                return View(  
                    _db.Products.  
                    Include(c => c.ProductTypes).  
                    Include(c => c.SpecialTag).  
                    Include(c => c.ProductTargets).  
                    Include(c => c.ProductTechs)  
                    .ToList());  
            }  
    

    Please tell me how in my case to catch in keyup only pressing the Enter key? And how can I use the ajax option to see the page Search.html only in @RenderBody()?

    Thanks!


  5. Bruce (SqlWork.com) 43,901 Reputation points
    2022-09-12T22:38:48.99+00:00

    the enter key does a form submit, so rather than use keyup, just use the form submit handler. in the callback just cancel the submit, and do the ajax call.

    $("#SearchInput").parent("form").submit(function(e) {  
       // cancel submit  
       e.preventDefault();  
      
       // do ajax call  
       ....  
      
    });  
    
    0 comments No comments