My application is MVC5 c#, trying to execute the following:
#{
var s = Model.PhysicalExam;
if (s == null)
{
<script>
alert("1");
$("#newSale1").hide();
</script>
}
else
{
<script>
alert("2");
$("#newSale1").show();
</script>
}
}
Alert works, however does not hide or show the button. Would appreciate your suggestions.
I would guess that newSale1 maybe isn't loaded in the DOM when that script code is executed. You should probably put those blocks inside a document ready event.
$( document ).ready(function() {
console.log( "ready!" );
});
I might go with something like this at the bottom of the page
<script type='text/javascript">
var isExamNull = #((Model.PhysicalExam == null).ToString());
$(document).ready( function(){
if (isExamNull)
$("#newSale1").hide();
else
$("#newSale1").show();
};)
</script>
Putting scripts at the bottom of the page lets the html render first, $(document).ready ensure that, well, the document is ready. Using the #() will write your server side values into your scripts, another technique is to use a hidden and have the script check the value of the hidden.
Related
Is it possible in javascript to open new aspx page by using javascript?.
I mean if I wants to open a new page in asp.net than I will use "Server.Transfer" method to open new aspx page the same thing I am asking over here to open new aspx page by using javascript.
Is it possible?.
I am trying as per your suggestion as below:
<script type="text/javascript">
$(document).ready(function()
{
function kpr(e)
{
if(e.which==17 && e.which==18 && e.which==82 || e.keyCode==17 && e.keyCode==18 && e.keyCode==82)
{
window.location.href="MemberInfo.aspx";
}
}
});
</script>
but it not allowed me to show new page as above........
Something like this (in the appropriate point in your script):
window.location.href = "OtherPage.aspx"
Try this in your client side function:
window.location.assign("Page.aspx")
Try using the debugging tools of your browser and set a checkpoint in your function to make sure that it actually gets to the window.location.href line.
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 :)
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.
i have an iframe that which source need to be updated and refreshed. the way i want to do it is to click on an and with it's onclick function, i need to send something like myiframe.Attributes["src"] = "blah.aspx";
is there any quick way to do this?
thanks in advance
You can use javascript to send an AJAX query back to the server with the frame's source.
The javascript you could use is iframe.location.href where 'iframe' is the id attribute of your iframe.
Then you can send a callback to the server using ASP.NET AJAX (or another ajax call if you wish). Here is a good tutorial: http://ajax.net-tutorials.com/
You could do it all client side if you wanted to (untested code):
...
<body>
<a id="yourAnchorId">Load It</a>
<iframe id="youriFrameId" src="blank.html" width="500" height="400"></iframe>
<script type="text/javascript">
document.getElementById('yourAnchorId').onclick = function() {
var frame = document.getElementById('youriFrameId')
frame.src = "blah.aspx;"
frame.location.reload();
};
</script>
</body>
...
Is there any javascript event which is triggered on postback?
If not, how can I run client side code immediately after or before a page postback?
I believe what you are looking for is the Sys.WebForms.PageRequestManager beginRequest Event
Excerpt:
The beginRequest event is raised before the processing of an
asynchronous postback starts and the postback is sent to the server.
You can use this event to call custom script to set a request header
or to start an animation that notifies the user that the postback is
being processed.
Code Sample: (From the link)
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args)
{
var elem = args.get_postBackElement();
ActivateAlertDiv('visible', 'AlertDiv', elem.value + ' processing...');
}
function EndRequestHandler(sender, args)
{
ActivateAlertDiv('hidden', 'AlertDiv', '');
}
function ActivateAlertDiv(visstring, elem, msg)
{
var adiv = $get(elem);
adiv.style.visibility = visstring;
adiv.innerHTML = msg;
}
</script>
I hope that helps. The PageRequestManager class seems to be little known about and little utilized.
Take a look at:
Run javascript function after Postback
I solved my problem using this:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function (s, e) {
alert('Postback!');
});
</script>
there are a lot of options too, like
$('#id').live('change', function (){});
$(document).ready(function () {});
ClientScriptManager.RegisterStartupScript(this.GetType(), "AKey", "MyFunction();", true);
and keep going. depends on what you need.
PageRequestManager events: https://learn.microsoft.com/en-us/previous-versions/aspnet/bb398976(v=vs.100)
You could add the javascript in your page load like this...
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert",
"alert('hello world');", true);
OR
Page.ClientScript.RegisterStartupScript(this.GetType(), "alertScript",
"function Hello() { alert('hello world'); }", true);
The Page.ClientScript object has a RegisterOnSubmitStatement This fires after any input submits the form. This may or may not be what you're looking for, but I've used it for notifying the user of unsaved changes in editable forms.
The advantage to using this over RegisterStartupScript is that with RegisterOnSubmitStatement, if a user navigates away and back using the browser, whatever script you've injected using RegisterStartupScript could possibly fire again, whereas RegisterOnSubmitStatement will only run if the user has submitted the form.
Use AJAX, with an event handler for the onComplete.
The onsubmit event on the form tag
When using jQuery it's like this
$("#yourformtagid").submit(function () {
...
}
There isn't a javascript event triggered when a page loads after a postback, but you can add javascript to your html template (.aspx file) and only run it if the page was posted, like this:
<script type='text/javascript'>
var isPostBack = '<%= this.IsPostBack%>' == 'True';
if (isPostBack) {
alert('It's a PostBack!');
}
</script>
If you want to customize the javascript to run only under particular conditions (not just any postback), you can create a page-level variable (protected or public) in your page's class and do something similar:
var userClickedSubmit = '<%= this.UserClickedSubmit%>' == 'True';
if (userClickedSubmit) {
// Do something in javascript
}
(Nothing against ClientScript.RegisterStartupScript, which is fine - sometimes you want to keep your javascript in the page template, sometimes you want to keep it in your page class.)