ASP.NET Core: how can I get Aajx to work within a ViewComponent? - c#

I wanted to have my comments section (including the "post comment" button) entirely contained within a ViewComponent so that my main page's html isn't as cluttered. Though it seems that Ajax fails to work within a ViewComponent.
The same code works fine in a razor page's .cshtml, but inside a ViewComponent (within my Pages/Shared/Components/AJAXTest/Default.cshtml, called with #await Component.InvokeAsync("AJAXTest")) it does nothing.
<button id="buttonDemo1">THE AJAX BUTTON</button>
#section Scripts
{
<script>
//edit: threw console.log around, nothing shows up in the browser console
$(document).ready(function () {
console.log("ready2!!");
var url = '#Url.Action("TEST", "ChatRoom")';
$('#buttonDemo1').click(function () {
console.log("THE FORBIDDEN BUTTON HAS BEEN PRESSED!");
$.ajax({
type: 'POST',
url: url,
success: function (result) {
alert(result);
}
});
});
});
</script>
}

Found the solution here: https://github.com/aspnet/Mvc/issues/2910#issuecomment-356276338 , tried it and it works.
For those who just stumpled here (aka TL;DR) you just have to define a layout on the viewcomponent.
Example:
_LayoutViewComponent.cshtml:
#RenderBody()
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
#RenderSection("Scripts", required: false)
YourViewComponentView.cshtml
#model YourModel
#{
Layout = "_LayoutViewComponent";
}
//html stuff
#section scripts
{
<script type="text/javascript">
//your scripting
</script>
}
But there's mention that Razor Components innately supports this here: https://github.com/dotnet/AspNetCore.Docs/issues/687#issuecomment-450596259 (though I am not familiar with how to use razor components yet). (realized that this is a Jquery related problem not an Ajax problem so the correct question to ask was "how can I get Jquery to work within a ViewComponent?" )

Related

Razor Pages Asp.Net-Core install FullCalendar

I am trying to install FullCalendar library to use in my Asp.Net Core Web App with Razor Pages and I installed the Nugget Package jQuery.FullCalendar.
In my Index.cshtml I use:
<div id="calendar"></div>
And in my site.js file I use:
$(function () {
$('#calendar').fullCalendar({
})
});
But when I run the app nothing happens. Did I missed some steps or this library is not working for Asp.Net Core?
For FullCalendar is a client-side library,I suggest that you could use LibMan.Refer to:
How to use LibMan.
Search for the js library:
1.moment.js:
2.FullCalendar.js:
Then your razor pages should like below:
<div id="calendar"></div>
#section Scripts
{
<link href="~/lib/fullcalendar/fullcalendar.min.css" rel='stylesheet' />
<script src="~/lib/moment.js/moment.min.js" ></script>
<script src="~/lib/fullcalendar/fullcalendar.min.js"></script>
<script>
$(function () {
$('#calendar').fullCalendar({});
})
</script>
}
Be sure your _Layout.cshtml is like below:
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
Note:If you do not apply _Layout to the razor pages,be sure add the jquery.js firstly then add moment.js and fullcalendar.js.The order could not change.
Another way is that you could use cdnjs without installing the js library:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.js"></script>
Result:

data-ajax-update not working in dotnet core jquery unobtrusive ajax

I want to update the data in my container with ajax data from a partial view but the page just reloads without errors and doesn't update the data. Please help me with advice.
Its my controller code
public class HomeController : Controller
{
public ActionResult OnGetPartial()
{
return PartialView();
}
}
Its my PartialView code
<p>Hello from the Hello World partial at #DateTime.Now</p>
its my index and _layout code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - IntegTest</title>
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
#RenderBody()
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
</script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script src="~/lib/jquery-validation/dist/additional-methods.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
#RenderSection("Scripts", required: false)
</body>
</html>
Index
Click Here!
<div id="panel">
</div>
<script>
completed = function (xhr) {
alert('hi ${xhr.responseText}!');
}
failed = function (xhr) {
alert('Status: { xhr.status }, Status Text: { xhr.statusText}');
}
</script>
You need to use jQuery Unobtrusive AJAX library , it can be find in Github :
https://github.com/aspnet/jquery-ajax-unobtrusive
You can download the file from above link(in src folder) or install it from Nuget in VS . Then you need to link the file in your _layout page :
<script src="~/lib/jquery-validation-unobtrusive/jquery.unobtrusive-ajax.js"></script>
After that your code should works well . In addition , you should ensure you have set correct partial view name . If you are using Razor pages , you can refer to this article for detail code sample .

How to use jquery in ASP.​NET Core

I created a ASP.NET core template and wrote a jquery script. When I look at the page I see that jquery is loaded into the page, but the script doesn’t run. I looked at the ASP.NET docs page and my layout.cshtml looks the same, so are there extra steps I must take to get jquery working?
Home page
#{
ViewData["Title"] = "Home Page";
}
<!-- Page Content-->
<div class="container">
<div class="row">
<form method="post" enctype="multipart/form-data">
<input type="file" id="files" name="files" multiple />
<input type="button" id="upload" value="Upload Selected Files" />
</form>
</div>
</div>
<script>
$(document).ready(function () {
alert("Test");
});
</script>
Solution
#section scripts
{
<script>
$(document).ready(function() {
alert("Test");
});
</script>
}
I suspect your jquery is loaded after the rest of the page content.
This means that you cannot reference jquery objects as the library has not been initialised yet.
Move the page script after jquery has loaded.
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$(document).ready(function () {
alert("Test");
});
</script>
For efficiency I recommend you do this in one of two ways:
OPTION 1
Use a master script file that loads after jquery.
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/master.js"></script>
OPTION 2
Use a placeholder template that will always load after jquery but can be initialised on individual pages.
Master _Layout Page
<script src="~/lib/jquery/dist/jquery.js""></script>
#RenderSection("Scripts", required: false)
Content Page
#section Scripts {
<script>
$(function () {
alert("Test");
});
</script>
}
FOR CLARIFICATION
If you are referencing jQuery in your _Layout page.. double check to ensure that that reference is at the TOP of your _Layout page because if it is at the bottom, then every other page you have that use the _Layout and has jQuery, it will give you errors such as:
$ is undefined
because you are trying to use jQuery before it is ever defined!
Also, if your are referencing jQuery in your _Layout page then you do not need to reference it again in your pages that use your _Layout style
Make sure that you are loading the reference to jQuery before you start using <scripts>.
Your cshtml should work if you put the reference above your script as so:
<script src="~/Scripts/jquery-1.10.2.js"></script> // or whatever version you are using
// you do not need to use this reference if you are already referencing jQuery in your Layout page
<script>
$(document).ready(function () {
alert("Test");
});
</script>
If you create a new .Net Core 2.2 - Web Application with Razor Pages and try to add a jQuery script in index.cshtml you will get the error Uncaught ReferenceError: $ is not defined. As already mentioned this is because jQuery is loaded after the rest of the page content.
Fix this by navigating to Pages\Shared\_Layout.cshtml and add the scripts section to the html head tag instead. Then it will work:
Example:
Move from below </footer>:
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
</environment>
<environment exclude="Development">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o">
</script>
</environment>
<script src="~/js/site.js" asp-append-version="true"></script>
#RenderSection("Scripts", required: false)
Into <head>, should look like this:
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - JiraApp.Clients.Web</title>
<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"
crossorigin="anonymous"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" />
</environment>
<link rel="stylesheet" href="~/css/site.css" />
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
</environment>
<environment exclude="Development">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o">
</script>
</environment>
<script src="~/js/site.js" asp-append-version="true"></script>
#RenderSection("Scripts", required: false)
</head>
Thanks to everyone who contributed to these answers. I am new to JavaScript/jQuery and have been trying to get jQuery scripts to work for over two weeks now. I have gotten a few examples to work but, until now, I had no idea why something worked or did not work.
All of the examples I have looked at online show the references to .js files at the bottom of the page. None of the examples explain how the _Layout.cshtml file works in relation to the Razor views in an application. It is so confusing to add the links and script references to the _Layout.cshtml file only to have it not work as expected. Next, I moved the links and references to a header section on the razor page and it still did not work. Now that I have everything organized correctly, it is working and I understand why!!!
The key was putting the script inside the #section Scripts {} block. I had seen the call to RenderSectionAsync but did not realize what it was doing. This is how the bottom of my _Layout.cshtml file looks now:
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery/dist/jquery.inputmask.min.js"></script>
<script src="~/lib/jquery/dist/inputmask.binding.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
#await RenderSectionAsync("Scripts", required: false)
I hope many new developers see this post. When it comes to an ASP Net Core application with Razor views, the information provided in this thread is priceless! Again, many thanks to everyone who contributed to the answer.
must write below first line in while where you want to execute script.
if you write first line in other wile, it is not working.
below example to test JQUERY work or not.
<script>
$(document).ready(function () {
alert("Test");
});
</script>
This is similar to the fullcalendar question posed here on Stackoverflow. I shared the following solution on that question --
This is a good reference for what has been asked here. I downloaded jQuery directly and unarchived it into the wwwroot/lib folder/directory to get going with my project - however as I needed more JS libraries, it seemed that the Nuget option of installing JS libraries into my project really was an impossible path/option.
Consider;
not sure why you would use nuget packages for javascript libraries. your example has not been updated in the last four years, and probably doesn't support .net core projects (may not even work a current version of jQuery).
you should be using a javascript repository and package mangers like bower or npm, that manages the dependencies between libraries.
That is from the linked MS Forum. Anyhow, the question can be flagged as a duplicate of the other Fullcalendar question (which was posed two years prior to this one).

Jquery UI in asp.net

How do i include jquery ui to be used in my system? I've already put the code in my header:
<script type="text/javascript" src="/scripts/jquery.min.js"></script>
And how can I include the date picker which I already downloaded from jqueryUI. Here is the code of the date picker :
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<div class="demo"><p>Date: <input type="text" id="datepicker"></p></div>
I got confused how to export the downloaded file to asp. Thank you.
Did you also include the references to JQuery?
<link type="text/css" href="css/themename/jquery-ui-1.8.23.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.23.custom.min.js"></script>
See: JQuery UI Documentation

how to implement datepicker in asp.net using jquery?

<script src="<%=("../Scripts/jquery-1.6.1.min.js") %>" type="text/javascript" />
<script src="<%=("../Scripts/jquery-datePicker.js") %>" type="text/javascript" />
<script type="text/javascript">
$(function() {
$("#txtDate").datepicker();
});
</script>
I have used this code but it doesnot show me the popup calender on click on textbox.
what can be the problem.
it doesnot give any error.
Perhaps you should use the document.ready function
$(document).ready(function() {
$("#txtDate").datepicker();
});
why not set path directly? and close script tag with this </script>
<script src="../Scripts/jquery-1.6.1.min.js" type="text/javascript" ></script>
<script src="../Scripts/jquery-datePicker.js" type="text/javascript" ></script>
Use ClientID for server control
<script type="text/javascript">
$(function() {
$("#<%= txtDate.ClientID %>").datepicker();
});
</script>
you can also use ready function
<script type="text/javascript">
$(document).ready(function() {
$("#<%= txtDate.ClientID %>").datepicker();
});
</script>
if ID selector doesn't work then use class selector it is good for ASP.NET server control
<asp:TextBox ruat="server" ID="txtDate" CssClass="DateField"></asp:TextBox>
<script type="text/javascript">
$(document).ready(function() {
$(".DateField").datepicker();
});
</script>
ID of ASP.NET server control is different than that of the normal HTML ID. So if you are using a Server control, then run your code, open the page source, get the ID that is displayed in the page source and use this ID instead of txtDate.
Also use
$(document).ready(function() { $("#<id>").datepicker(); });

Categories

Resources