In select tag, there is a function loadTags(), which is called on onclick event. I am using mvc4 and want to call it with _layout.cshtml i.e shared view:
<div class="left-menu">
<select id="tid" name="tags" onclick="loadTags()" >
<option value="tags">--Tags--</option>
</select>
</div>
How should I call this function on page load. Here is loadTags() function
function loadTags() {
$("#tid option").remove();
var d = $("#tid").val();
var str = "--Tags--";
$.post("/Status/allTags", function (data) {
$("#tid").append('<option>' + str + '</option>');
$.each(data, function (i, item) {
$("#tid").append('<option value=' + i + '>' + item + '</option>');
});
}, "json");
}
Just use jQuery?
$(function() {
loadTags();
});
Make sure jQuery is loaded before you call this line of code.
I don't think loading the tags when the user clicks the element is a good approach. For instance, when the user uses the tab key to navigate to this element, the tags will not load.
Also, if you are loading the tags on page load, does it still make sense to load them via AJAX? Can't you include them in the page itself?
put your code in document.ready function:
$(document).ready(function () {
loadTags();
});
or shorter:
$(function () {
loadTags();
});
or even shorter:
$(loadTags);
jfiddle
.ready():
While JavaScript provides the load event for executing code when a
page is rendered, this event does not get triggered until all assets
such as images have been completely received. In most cases, the
script can be run as soon as the DOM hierarchy has been fully
constructed. The handler passed to .ready() is guaranteed to be
executed after the DOM is ready, so this is usually the best place to
attach all other event handlers and run other jQuery code. When using
scripts that rely on the value of CSS style properties, it's important
to reference external stylesheets or embed style elements before
referencing the scripts.
Related
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.
I am using jQuery mobile in my project and when I log on to system, then go to change password page, the change action is not firing (no action). But, when I refresh the page, it is firing. Briefly, the button on the page is not working when it is redirected from another page except itself. I have imported .css and .js files correctly in master page. (Generic Handler returns correct values and it is working)
head content:
<script type="text/javascript">
$(document).ready(function () {
$("#changePasswordBtn").click(function () {
$.ajax({
type: "POST",
url: "ChangePasswordHandler.ashx",
data: "oldPassword=" + $("#oldPassword").val() + "&newPassword=" + $("#newPassword").val() + "&reNewPassword=" + $("#reNewPassword").val(),
success: function (msg) {
if (msg == 0) $("#popupText").text("success");
else if (msg == 1) $("#popupText").text("wrong pass");
else if (msg == 2) $("#popupText").text("match error");
else if (msg == 3) $("#popupText").text("fill boxes");
else $("#popupText").text("error");
}
});
})
});
</script>
body content:
<input type="button" id="changePasswordBtn" value="Change Password" data-inline="true" />
I have seen a similar problem in my project. Make sure that you are using different ids for buttons.
If the ids are same then the click event is not attached to the right button.
I got a workaround for this issue by changing the way I load my pages.
I put target="_self" into the href element so it don't load using the # system - this way the javascript loads with the initial page load while navigating from one page to a nother.
I will put the below link on my index.html page that will navigate to my signup.html page.
Signup
NOTE: You will lose the 'fancy' jQuery Mobile page transition feature
Here is the context:
I am building a .aspx page that allows the user to administrate some xml documents we have on our server. The page content is loaded using AJAX, so buttons and forms are dynamically added to the document.
If I had static buttons that I was creating within the .aspx page before it loads on the client's machine, I could attach an event to it very easily. However, I'm dynamically adding and removing buttons and forms on the fly, using jQuery.
Here is a simplified example:
In the following jsFiddle, I'm pretending that the html document contains the following script:
<script language="C#" type="text/C#" runat="server">
void SaveAllChanges(Object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
clickedButton.Text = "foobar";
}
</script>
And that I have a javascript file that contains the following:
$('button.buttonGenerator').click(function() {
$('.buttonContainer').append(
'<button onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
});
Obviously the buttons I am creating can not run the function SaveAllChanges with the way it is now. I added the onclick attribute to show what I needed to happen, in a pseudo-code kind of style.
How can I make it so that dynamically added buttons can run the C# method I have defined within the script tag at the top of the document?
Here is the jsfiddle: http://jsfiddle.net/2XwRJ/
Thanks.
You can give all buttons that must save changes a common class (e.g. class="ajaxButton") and have one jQuery method that responds to click events on elements matching that class (use live so that updates to the DOM are reflected).
$("button.ajaxButton").live("click", function(){
// Perform your Ajax callback to run server-side code
});
What you need to do is use something like ..
$(document).ready(function() {
$('button.buttonGenerator').click(function() {
$('.buttonContainer').append(
'<button id="#dynamicCommentButton" onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
});
$(document).on('click', '#dynamicCommentButton', function() {
alert($(this).attr('id'));
});
});
You are not going to be able to add the buttons like you have it there as this code here is just adding it as an HTML DOM element and the onclick attribute will be the on the client element. As a result clicking the button will try fire a SaveAllChanges javascript function
$('.buttonContainer').append(
'<button onclick="SaveAllChanges">' +
'Save All Changes!' +
'</button>'
);
What would be best would be to create that SaveAllChanges function in javascript and then you can handle it from there. Two of the ways I see you being able to do this are:
Have a http endpoint setup (script service, web api or just posting to a page) that you call using Ajax from your javascript. You can then pass through any needed arguments.
You could have a hidden element and hidden button on the page so that when the javascript is called it populates any arguments you need and then clicks the hidden button and posts the page back.
Personally I would choose the first approach from a user experience stand point as the page will not be posting back each time. I have used something similar to the second approach and it works fine but just feels very clunky.
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 :)
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.)