jquery function, make call in aspx razor - c#

I would like to call a jquery function in razor, but i can't do it, why?
ClientScript.RegisterStartupScript(Page, GetType(), "success", "alert("");", true);
It says that it's not defined...

ClientScript.RegisterStartupScript() is for web forms. If you want to call a JavaScript function in a Razor template, embed the call in the template.
There are many different ways to accomplish this. In this example, the view model contains a flag that is used to conditionally output a block of script to the client.
#model MyModel
<div>
Some code in the view...doesn't matter
</div>
#if( MyModel.ShowSuccessAlert ){
<script>
alert("Success!");
</script>
}

Related

Repeating HTML section in Razor Pages

I have a block of HTML I need to render in multiple places on a page, and I'm looking for a way to only define that HTML once. I can't rely simply on a loop because the HTML appears in different areas.
I know I can use a partial view. But since the block of HTML will only be displayed one one page, I'd prefer to define it there.
I know I can create a #functions block to create a function to render the markup, but this is geared towards code and not markup. I'd like something more like #helper functions in MVC, but those don't appear to be available in Razor Pages.
Can anyone offer other suggestions for defining a block of HTML in one place so it can be shown anywhere on the page?
If you are working with .NET Core 3, you can include HTML tags in methods declared in an #functions block e.g.
#functions{
void Greeter()
{
<h3>Hello World</h3>
}
}
Then in the content part of the page:
#{ Greeter(); }
The kind of helper can also take parameters:
void Greeter(string greeting)
{
<div>#greeting World</div>
}
#{ Greeter("Hello"); }
If you are working with ASP.NET Core 2.x, your "helper" method is a Func<someType, IHtmlString>. In the following example, the someType is a string:
Func<string, IHtmlContent> Greeter = #<h1>Hello #item</h1>;
Then in the content part of the page:
#Greeter("World");
someType can be a complex type:
Func<Contact, IHtmlContent> Greeter = #<h1>Hello #item.FirstName</h1>;
Template tag can help:
<template id="block-template">
<div>
<p>template contents...</p>
</div>
</template>
<div id="target1"></div>
<script>
var tmplt = $("#block-template").html();
$("#target1").append(tmplt);
</script>
the template tag is available in HTML5, you can also use script template :
<script id="block-template" type="text/template">
<div>
<p>template contents...</p>
</div>
</template>
there is a lot of plugins to use if you need to bind data to the template :
http://handlebarsjs.com/
https://github.com/jcgregorio/stamp/
https://knockoutjs.com/documentation/template-binding.html
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template

The following sections have been defined but have not been rendered for the layout page “~/Views/Shared/_Layout.cshtml”

I've this ActionResult:
[EncryptedActionParameter]
[CheckExternalUserRegisterSigned]
public ActionResult ExpedienteIIT(int idExpediente)
{
ExpedienteContainerVM model = this.GetExpedienteVMByIdExpediente(idExpediente);
return View("ExpedienteIIT", model);
}
ExpedientIIT View:
https://jsfiddle.net/pq16Lr4q/
_Layout.cshtml:
https://jsfiddle.net/1ksvav43/
So when I return the view I got this error:
I tried to put console.logs to see if the view is rendered but is not rendered...
Ok the error is here:
#model PortalSOCI.WEB.ViewModels.IIT.ExpedienteContainerVM
#{
ViewBag.Title = String.Format(PortalSOCI.WEB.Resources.ExpedienteIIT.TituloExpedienteIIT, Model.Expediente.NumeroExpediente);
}
#section JavaScript /// <-------------------- ERROR
{
#Html.Raw(ViewBag.message)
#
Can you please help me.
edit:
After reading your code, i feel like
#RenderSection("scripts", required: false)
should be
#RenderSection("JavaScript", required: false)
an other thing that I think will give you trouble is the fact that you define your "JavaScript" section in the body. This means that if any of your views you forget to add that
#section JavaScript
{
#Html.Raw(ViewBag.message)
}
you'll get a Section JavaScript not defined error. In your case, feels like the section's definition should be in the _layout.cshtml.
This error most likely means that you have defined the JavaScript section but have not rendered it anywhere.
You need to call #RenderSection("JavaScript") somewhere in your layout.cshtml
the
#section JavaScript
{
}
will let you create a section called "JavaScript", but to actually "print" the content of this section to the output HTML file (that will be sent to the client) you need to call #RenderSection("JavaScript"). The content of the section will be printed where the call to RenderSection is located.
You need to put the missing section inside your ExpedienteIIT view. According to the error message, that missing section is JavaScript.
Code sample, put this at the bottom of your view:
#section JavaScript
{
// put javascript here
}
EDIT:
Thank you for providing a code sample of your views. There is a mismatch between how the JavaScript section in your layout page is defined and how it is being included in your view.
To fix this, do either one of the following:
In your _Layout page, change #RenderSection("scripts", required: false) to #RenderSection("JavaScript", required: false), OR
In your ExpedienteIIT view, change #section JavaScript to #section scripts
The important thing is that the two should match.

How to share information between partial views in JS

Two partials loaded on the same page
For example, if I hit a button in one partial then I want some value to appear in the other partial.
I want all the work to be done on the client side. I am sure I would call a method in js but I am not sure how to connect it to another js var on another partial within the same page. In other words how do I get both the partials to talk to eachother on the client side.
Once your razor view is rendered to the browser, It is just HTML markup. That means, you can use javascript to access the elements in the DOM and update the values as needed.
Keep your script in the main view which holds the 2 partial views.
$(function(){
$("#ButtonInFirstParial").click(function(e){
e.preventDefault();
$("#DivInSecondPartial").html("Updated");
});
});
Also if you declare your javascript variable in a global scope, you can access it in other places also. So if you have a variable like this in your layout page,
<body>
#RenderBody()
<script type="text/javascript">
var global_SiteUrl="Some value i want to access in all pages";
</script>
</body>
You can access it in other views (which uses the above one as the Layout), or js files which are a part of other views who has the layout value set as the above layout.

Add CSS and JS in AJAX-loaded PartialView

I found many answers about similar topics but all refers to PartialViews loaded not by AJAX where solutions are e.g. HtmlHelpers or Head section, but it doesn't work when I load PartialView by AJAX.
I wanna add CSS stylesheet and JS script inside AJAX-loaded PartialView. Now I coded it inside PartialView and it works but it's not good solution (include scripts and stylesheets inside body).
Everything should work just fine except validation. You need to tell jQuery about your new content on order to validate it.
See
ASP.Net MVC: Can you use Data Annotations / Validation with an AJAX / jQuery call?
If you are only loading the PartialView once onto the page, there should be no problem including the scripts and CSS in the body. Like Adam said if you are including a HTML Form dynamically you just have to tell jQuery about it see here ASP.Net MVC 3 client side validation with a dynamic form
However if you want to include the same PartialView multiple times on to the page and do not want to load the script multiple times. Then there are dynamic script loaders you can use that:
You can call just one from your main page, when you load the AJAX so that it is only included once
Include a check to make sure the same script is not loaded multiple times.
I didn't know that earlier that using script tag inside body is not evil. So it's not that bad I thought at first.
I implemented two functions in cssLink.js which I include in head:
/// <reference path="../jquery-1.4.4.js" />
function addCssLink(link) {
var _cssLink = '<link rel=\"stylesheet\" href=\"' + link + '\" type=\"text/css\" />';
$head = $('head');
$link = $('link[href=' + link + ']', $head);
if ($link.length == 0) {
$head.append(_cssLink);
}
}
function removeCssLink(link) {
$('head link[href=' + link + ']').remove();
}
and I use those functions within PartialViews:
<script type="text/javascript">
$(document).ready(function () {
$('#sideMenu').tabs('#content', '#content > *');
addCssLink('/Content/SideMenu.css');
});
</script>
<script type="text/javascript">
$(document).ready(function () {
removeCssLink('/Content/SideMenu.css');
});
</script>
Thank you guys for help, I think that informations about validation should be helpful for me later :)

asp.net accessing javascript variables after ajax updatepanel

I'm using AJAX on an ASP.NET web project to update a page. Some of my functions return XML that I want to embed on the page after it reloads. This part works, here's a sample of how it looks at the top of the page:
var productXML = "<?xml version=\"1.0\"?><ArrayOfProduct xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Product><ActualProdID>123</ActualProdID><Name>Test</Name><Description>Test</Description><Edition>Test</Edition><Platform>Test</Platform><Family>Test</Family><Type>Test</Type><DeploymentTypes>Test</DeploymentTypes><BaseActualProdID>Test</BaseActualProdID><Price>0</Price></Product></ArrayOfProduct>";
Later in the page I'm trying to use the XML but it's not working. I tried to do something simple and just throw an alert box in that looks like this:
<script type="text/javascript">
function closeLoading()
{
jQuery('.pleaseWaitPanel').css({ 'display': 'none', 'visibility': 'hidden' });
alert("here");
alert(productXML);
alert("here2");
}
</script>
closeLoading() is called inside:
window.onload = function () { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading); };
It loads the jQuery and the first alert "here" works perfect. When I go to alert the productXML, nothing happens. It doesn't throw a JavaScript error, I'm using Firebug. I can confirm the XML is on the page.
Any help on this would be GREATLY appreciated!!
From your code snippets, it looks like your closeLoading function is only being called in your window.onload function. This means that it won't be called after any Ajax request completes as the window won't be reloaded.
I would try moving your call to Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading) to just before your closing server-side form tag:
<form runat="server">
...
<script>
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading);
</script>
</form>
Hope this helps.
var productXML
Is a ServerSide variable, so you don't have access to this in Client script.
If you want to use in a javascript function you can do this :
1) Put the result in a textbox hidden, like
<input type='hidden' value='<%=productXML%>'>
then simply get the value of the textbox.

Categories

Resources