ClientId is different in localhost and the webserver - asp.net

I am facing a new kind of problem.
I am using the jQuery to fill the state dropdown on the change of country dropdown and the code of the jquery is on a js file so i bind the static client id like ct100_ddlCountry, this is working properly on the localhost but when i host this website to web server it not working because the client generating on the server is _ct100_ddlCountry.
Please tell me something if anyone has an idea about this. I am new to this kind of problem.
Thanks to all.

If you can't upgrade to .NET 4.0 for clean id's, I wrote a small lib and shoved it on CodePlex to serialize controls to a JSON array on the client.
http://awesomeclientid.codeplex.com/
http://www.philliphaydon.com/2010/12/i-love-clean-client-ids-especially-with-net-2-0/
It serializes the controls and outputs some JavaScript like:
<script type=”text/javascript”>
//<![CDATA[
var controls = {
"txtUserName": "ctl00_ContentPlaceHolder1_txtUserName",
"txtEmail": "ctl00_ContentPlaceHolder1_txtEmail",
"btnSubmit": "ctl00_ContentPlaceHolder1_btnSubmit"
};
//]]>
</script>
Which then allows you to access controls like:
<script type=”text/javascript”>
//<![CDATA[
var element = document.getElementById(controls.btnSubmit);
//]]>
</script>
No need to write spaghetti code :)
Edit: Alternatively, you can use jQuery selectors to do something like:
var control = $('[id*=txtEmail]');

It is not normally good practice to hard code control ids in your js script includes or html source.
Try using something like this:
JS
function DoChange(controlid) {
$("#"+controlid);
}
HTML
<select onchange='DoChange("<%= ddlCountry.ClientID %>");' />
It means if you move your control around in your control tree, then you dont break your code, and it should work on your localhost and IIS
UPDATE
Or like this
JS
function DoChange(control) {
$(control);
}
HTML
<select onchange="DoChange(this);" />

If it is ASP.Net 4.0 then you can use ClientIDMode="Static" to make sure that only IDs provided by you are there on final markup.
Or you can use something like $('id$=country'). $ is used to match the end of Id, but I am sure that is something not optimal.

Related

Why do my MVC application gives errors on a cloud server? [duplicate]

I have a simple jquery click event
<script type="text/javascript">
$(function() {
$('#post').click(function() {
alert("test");
});
});
</script>
and a jquery reference defined in the site.master
<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript"></script>
I have checked that the script is being resolved correctly, I'm able to see the markup and view the script directly in firebug, so I must be being found. However, I am still getting:
$ is not defined
and none of the jquery works. I've also tried the various variations of this like $(document).ready and jQuery etc.
It's an MVC 2 app on .net 3.5, I'm sure I'm being really dense, everywhere on google says to check the file is referenced correctly, which I have checked and checked again, please advise! :/
That error can only be caused by one of three things:
Your JavaScript file is not being properly loaded into your page
You have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $ variable.
You have JavaScript running before the page is fully loaded, and as such, before jQuery is fully loaded.
First of all, ensure, what script is call properly, it should looks like
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
and shouldn't have attributes async or defer.
Then you should check the Firebug net panel to see if the file is actually being loaded properly. If not, it will be highlighted red and will say "404" beside it. If the file is loading properly, that means that the issue is number 2.
Make sure all jQuery javascript code is being run inside a code block such as:
$(document).ready(function () {
//your code here
});
This will ensure that your code is being loaded after jQuery has been initialized.
One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described.
Note: If you're loading code which does not require jQuery to run it does not need to be placed inside the jQuery ready handler. That code may be separated using document.readyState.
It could be that you have your script tag called before the jquery script is called.
<script type="text/javascript" src="js/script.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
This results as $ is not defined
Put the jquery.js before your script tag and it will work ;) like so:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/script.js"></script>
First you need to make sure that jQuery script is loaded. This could be from a CDN or local on your website. If you don't load this first before trying to use jQuery it will tell you that jQuery is not defined.
<script src="jquery.min.js"></script>
This could be in the HEAD or in the footer of the page, just make sure you load it before you try to call any other jQuery stuff.
Then you need to use one of the two solutions below
(function($){
// your standard jquery code goes here with $ prefix
// best used inside a page with inline code,
// or outside the document ready, enter code here
})(jQuery);
or
jQuery(document).ready(function($){
// standard on load code goes here with $ prefix
// note: the $ is setup inside the anonymous function of the ready command
});
please be aware that many times $(document).ready(function(){//code here}); will not work.
If the jQuery plugin call is next to the </body>, and your script is loaded before that, you should make your code run after window.onload event, like this:
window.onload = function() {
//YOUR JQUERY CODE
}
`
so, your code will run only after the window load, when all assets have been loaded. In that point, the jQuery ($) will be defined.
If you use that:
$(document).ready(function () {
//YOUR JQUERY CODE
});
`
the $ isn't yet defined at this time, because it is called before the jQuery is loaded, and your script will fail on that first line on console.
I just did the same thing and found i had a whole lot of
type="text/javacsript"
So they were loading, but no further hint as to why it wasn't working. Needless to say, proper spelling fixed it.
Use a scripts section in the view and master layout.
Put all your scripts defined in your view inside a Scripts section of the view. This way you can have the master layout load this after all other scripts have been loaded. This is the default setup when starting a new MVC5 web project. Not sure about earlier versions.
Views/Foo/MyView.cshtml:
// The rest of your view code above here.
#section Scripts
{
// Either render the bundle defined with same name in BundleConfig.cs...
#Scripts.Render("~/bundles/myCustomBundle")
// ...or hard code the HTML.
<script src="URL-TO-CUSTOM-JS-FILE"></script>
<script type="text/javascript">
$(document).ready(function () {
// Do your custom javascript for this view here. Will be run after
// loading all the other scripts.
});
</script>
}
Views/Shared/_Layout.cshtml
<html>
<body>
<!-- ... Rest of your layout file here ... -->
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
Note how the scripts section is rendered last in the master layout file.
It means that your jQuery library has not been loaded yet.
You can move your code after pulling jQuery library.
or you can use something like this
window.onload = function(){
// Your code here
// $(".some-class").html("some html");
};
As stated above, it happens due to the conflict of $ variable.
I resolved this issue by reserving a secondary variable for jQuery with no conflict.
var $j = jQuery.noConflict();
and then use it anywhere
$j( "div" ).hide();
more details can be found here
make sure you really load jquery
this is not jquery - it's the ui!
<script language="JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js">
</script>
This is a correct script source for jquery:
<script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
Are you using any other JavaScript libraries? If so, you will probably need to use jQuery in compatibility mode:
http://docs.jquery.com/Using_jQuery_with_Other_Libraries
after some tests i found a fast solution ,
you can add in top of your index page:
<script>
$=jQuery;
</script>
it work very fine :)
I had the same problem and resolved it by using
document.addEventListener('DOMContentLoaded', () => {
// code here
});
I got the same error message when I misspelled the jQuery reference and instead of type="text/javascript" I typed "...javascirpt". ;)
It sounds like jQuery isn't loading properly. Which source/version are you using?
Alternatively, it could a be namespace collision, so try using jQuery explicitly instead of using $. If that works, you may like to use noConflict to ensure the other code that's using $ doesn't break.
That error means that jQuery has not yet loaded on the page. Using $(document).ready(...) or any variant thereof will do no good, as $ is the jQuery function.
Using window.onload should work here. Note that only one function can be assigned to window.onload. To avoid losing the original onload logic, you can decorate the original function like so:
originalOnload = window.onload;
window.onload = function() {
if (originalOnload) {
originalOnload();
}
// YOUR JQUERY
};
This will execute the function that was originally assigned to window.onload, and then will execute // YOUR JQUERY.
See https://en.wikipedia.org/wiki/Decorator_pattern for more detail about the decorator pattern.
I use Url.Content and never have a problem.
<script src="<%= Url.Content ("~/Scripts/jquery-1.4.1.min.js") %>" type="text/javascript"></script>
In the solution it is mentioned -
"One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described."
For avoiding this -
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict():
I had this problem once for no apparent reason. It was happenning locally whilst I was running through the aspnet development server. It had been working and I reverted everything to a state where it had previously been working and still it didn't work. I looked in the chrome debugger and the jquery-1.7.1.min.js had loaded without any problems. It was all very confusing. I still don't know what the problem was but closing the browser, closing the development server and then trying again sorted it out.
Just place jquery url on the top of your jquery code
like this--
<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#post').click(function() {
alert("test");
});
});
</script>
I had the same problem and it was because my reference to the jQuery.js was not in the tag. Once I switched that, everything started working.
Anthony
Check the exact path of your jquery file is included.
<script src="assets/plugins/jquery/jquery.min.js"></script>
if you add this on bottom of your page , please all call JS function below this declaration.
Check using this code test ,
<script type="text/javascript">
/***
* Created by dadenew
* Submit email subscription using ajax
* Send email address
* Send controller
* Recive response
*/
$(document).ready(function() { //you can replace $ with Jquery
alert( 'jquery working~!' );
});
Peace!
This is the common issue to resolve this you have to check some point
Include Main Jquery Library
Check Cross-Browser Issue
Add Library on TOP of the jquery code
Check CDNs might be blocked.
Full details are given in this blog click here
I came across same issue, and it resolved by below steps.
The sequence of the scripts should be as per mentioned below
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
This sequence was not correct for my code, I corrected this as per the above and it resolved my issue of Jquery not defined.
We have the same problem....but accidentally i checked folder properties and set something...
You have to check the properties of each folders that you're accessing..
right click folder
'permissions' tab
set the folder access :
OWNER: create and delete files
GROUP: access files
OTHERS: access files
I hope that this is the solution......
When using jQuery in asp.net, if you are using a master page and you are loading the jquery source file there, make sure you have the header contentplaceholder after all the jquery script references.
I had a problem where any pages that used that master page would return '$ is not defined' simply because the incorrect order was making the client side code run before the jquery object was created. So make sure you have:
<head runat="server">
<script type="text/javascript" src="Scripts/jquery-VERSION#.js"></script>
<asp:ContentPlaceHolder id="Header" runat="server"></asp:ContentPlaceHolder>
</head>
That way the code will run in order and you will be able to run jQuery code on the child pages.
In my case I was pointing to Google hosted JQuery. It was included properly, but I was on an HTTPS page and calling it via HTTP. Once I fixed the problem (or allowed insecure content), it fired right up.
After tried everything here with no result, I solved the problem simply by moving the script src tag from body to head
I was having this same problem and couldn't figure out what was causing it. I recently converted my HTML files from Japanese to UTF-8, but I didn't do anything with the script files. Somehow jquery-1.10.2.min.js became corrupted in this process (I still have no idea how). Replacing jquery-1.10.2.min.js with the original fixed it.
it appears that if you locate your jquery.js files under the same folder or in some subfolders where your html file is, the Firebug problem is solved. eg if your html is under C:/folder1/, then your js files should be somewhere under C:/folder1/ (or C:/folder1/folder2 etc) as well and addressed accordingly in the html doc. hope this helps.
I have the same issue and no case resolve me the problem. The only thing that works for me, it's put on the of the Site.master file, the next:
<script src="<%= ResolveUrl("~/Scripts/jquery-1.7.1.min.js") %>" type="text/javascript"></script>
<script src="<%= ResolveUrl("~/Scripts/bootstrap/js/bootstrap.min.js") %>" type="text/javascript"></script>
With src="<%= ResolveUrl("")... the load of jQuery in the Content Pages is correct.

simple script to apply bootstrap pagination style in asp.net gridview

is there any simple jquery script/plugin to apply bootstrap pagination style in asp.net gridview ? I've found some good tips about how to do this, like these links: here and here.
the only problem with these tips/solutions is we need to make a lot of changes to achieve the result and this is not preferable when you have large application and you want to transform it to bootstrap style. we need another solution. like a simple jquery script that can do the job without making lot changes to the current code.
I've made simple jquery script to apply the bootstrap pagination in asp.net gridview and I think it will be useful to share it here in stackoverflow.
source code of this script is hosted in github here.
usage is very simple:
-include the plugin js file in your asp.net page file:
<script type="text/javascript" src="js/bs.pagination.js"></script>
-set gridview property:
PagerStyle-CssClass="bs-pagination"
that's is all you need to apply bootstrap pagination style in asp.net gridview.
check my blog for more info.
Edit:
about the problem when using gridview inside UpdatePanel, the reason of this problem is because “UpdatePanel completely replaces the contents of the update panel on an update. This means that those events we subscribed to are no longer subscribed because there are new elements in that update panel.”
There is more than one solution to solve this problem:
Solution 1:
Use pageLoad() instead of $(document).ready. Modify the code like this:
function pageLoad() {
$('.bs-pagination td table').each(function (index, obj) {
convertToPagination(obj)
});
}
Solution2:
re-change the style after every update. We can do this by adding these lines to the bs.pagination.js file:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
$('.bs-pagination td table').each(function (index, obj) {
convertToPagination(obj)
});
});

How to change img src on document ready before browser downloads images?

On my page I have some images on thisdomain.com/images. on document.ready(), I change the src attribute of images to thatdomain.com/images. Firebug's Net tab shows me that images are downloaded from both thisdomain.com and thatdomain.com. How can I prevent the browser from downloading images from thisdomain.com?
$(document).ready(function(){
$("img").each(function() {
var $img = $(this);
var src = $img.attr("src");
$img.attr("src", src.replace(/thisdomain.com.com\/images/i, "thatdomain.com\/images"));
});
});
EDIT: ASP.NET server-side override of Render() using code "in front" i.e., <script runat="server"> I just added this to the aspx page without recompiling code-behind. It's a bit hack-ish but it works.
<script runat="server">
static Regex rgx = new Regex(#"thisdomain.com/images", RegexOptions.Compiled | RegexOptions.IgnoreCase);
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
{
base.Render(htmlwriter);
string html = htmlwriter.InnerWriter.ToString();
string newHtml = rgx.Replace(html, "thatdomain.com/images");
writer.Write(newHtml.Trim());
}
}
</script>
This sounds like something that is impossible to achieve reliably, because images will start to load asynchronously as soon as a src has been specified.
I can't think of a workaround. The <base> tag would allow for some kind of "mass redirection" but the URIs would have to be relative ones for that to work.
I'm sure you have your reasons for outputting thisdomain.com in the first place, but I'm pretty sure you'll have to change your code so thatdomain.com gets output instead (or no src gets specified at all so you can add them using jQuery) if you want a 100% watertight solution.
This ain't going to work in the client side. Your best bet is a server side solution. Have the server side script (PHP? JSP? ASP? etc) to read the to-be-included HTML source and replace the src's accordingly with help of a decent DOM parser before it get emitted to the client side.
I don't that is possible at all. To use jQuery functions, the jQuery library needs to be downloaded, which probably means the browser already started downloading other assets, such as images.
You can't be completely sure to prevent downloading by changing the URL after the element has been parsed. The closest possible that you can get is by changing it immediately after the element:
<img id="something" src="http://www.thisdomain.com/images/hello.gif" />
<script type="text/javascript">
var $img = $('#something');
$img.attr("src", $img.attr("src").replace(/thisdomain.com\/images/i, "thatdomain.com\/images"));
</script>
I don't think there is a way to halt GET requests from img elements once the page has loaded. It's difficult to suggest an alternative since I'm not sure what you're trying to achieve.
Can you be more specific?

Unobtrusive JavaScript with server side values, best practice?

I'm used to do doing things like this:
<a href="Javascript:void(0);" onclick="GetCommentForGeneralObservation(<%# Eval("ID") %>)">
That would be in a repeater or such like btw. However I an now trying to use unobtrusive JavaScript and hence get rid of any JS in the markup. I was trying to figure out what the best practice is in cases like this? I've used attributes and then got the value using JQuery to pass to the AJAX call but it seems a bit of a hack.
Edit in light of first reply:
I was thinking more of the
Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation.
part of unobtrusive JS as I understand it.
This happens to be for an application where I don't have to worry about Javascript being turned off on the client, it's hosted internally at my company. What I was getting at was how would I get the value from Eval("ID") into the JS call if I were to attach the onclick event in a separate .js file via JQuery.
Sorry for not being clearer. I appreciate the need for progressive enhancement in public facing apps.
In HTML 5 you are allowed to define your own attributes prefixed with 'data-'
e.g.
<a
class="comment"
data-rendered-id="<%# Eval("ID") %>"
href="/getCommentForGeneralObservation/<%# Eval("ID") %>" >
And then use that attribute in jQuery in your click event handler.
$(".comment").click(function () {
var id = $(this).attr("data-rendered-id");
return GetCommentForGeneralObservation(id);
});
This will work in most pre-HTML5 browsers too as long as they support jQuery.
Note that in unobtrusive javascript you really should support non-javascript browsers, hence you need an href attribute that works as well.
I'd start with:
<a href="/getCommentForGeneralObservation/<%# Eval("ID") %>" class="getCommentForGeneralObservation">
and then attach an event handler that looked something like this:
function (event) {
var href = this.href;
var id = href.search(/\/(\d+)/);
return GetCommentForGeneralObservation(id);
};
Unobtrusive means you don't depend on Javascript for functionality and therefore your code is extended with Javascript rather than replaced by it.
In your case, you're embedding Javascript directly in the link, and worse off, the link won't work at all without Javascript enabled. Instead you'll want something like this, which is pure HTML without any reference to Javascript:
<a id="commentLink" href="comment.asp">Get Comment</a>
And your Javascript (assuming you're not using a framework) would be something like:
function GetCommentForGeneralObservation(evt) {
// Extra javascript functionality here
}
document.getElementById("commentLink").onclick = GetCommentForGeneralObservation;
With Jquery I believe you could just do:
$("#commentLink").click(GetCommentForGeneralObservation);
I'm going to re-answer this because I understand the question now and the approach I usually use is different from what has been suggested so far.
When there's no way to avoid having dynamic content, I will usually do the following:
<script type="text/javascript">
var myApp = {commentId:<%# Eval("ID") %>};
</script>
<script type="text/javascript" src="myAppScript.js"></script>
Now, in myAppScript.js, you can use myApp["commentId"] wherever you need that ID to be referenced. (I use a dictionary so as to not pollute the global namespace)
The advantage of this approach is that your myAppScript.js is still completely static and so you can serve it very fast. It also has the advantage of keeping the relevant information out of the URL and you can use Javascript objects, which can help a lot with complex and/or hard-to-parse data.
The disadvantage is that it requires inline Javascript, which isn't much of a disadvantage unless you're a web perfectionist.
I also really like DanSingerman's approach, which is more suited if your data is specific to a tag.
You might wish to use JQuery metadata plugin, or the core data function.
http://docs.jquery.com/Core/data
http://plugins.jquery.com/project/metadata
You could use the rel attribute of the anchor tag to store the value you want to associate with the link.
Click Here
Then in your jQuery code you can check the rel attribute to get the value you're looking for.
$(".comment").click(function () {
return GetCommentForGeneralObservation(this.rel);
});
(Pretty sure this is accurate for jQuery, but I'm more of a MooTools guy...)
How about making sure it is fully unobtrusive?
In the head of the HTML document
<script src="path/to/php/or/other/equivalent/server/side/file"></script>
In the path/to/php/or/other/equivalent/server/side/file:
var SiteServerVariablesEtc = {
someProperty: <?php echo "hello" ?>
}
In your normal JS file:
var myVar = SiteServerVariablesEtc.someProperty;

Alternatives to Iframe

I have been developing a service that allows users to insert information from my database onto their sites by using iframes. The only problem was that the iframe needs to be resizeable and this is one of the biggest problems with iframes as most people already know, aswell as the fact I can access objects on the parent page from within the iframe and vice versa.
I have thought of making an asp.net web servie to server up the HTML and access it by using a get request. However this also has a problem since these request can only be made from the same domain?
What I need to know is the best way to retrieve a small piece of HTML containing customer reviews from server and display it on their page using some sort of AJAX.
Thanks
if your users can add a < script > line to their site pointing to code on your site, you can fairly easily offer a mechanism to build a floating (and resizable) DIV on their page that you jquery.load() with content from your site ...
example:
"To use my service on your site, add the following line to your < head >"
<script type='text/javascript' src='http://mysite.com/scripts/dataget.js />
then add a link or button anywhere and give it a class 'get-date-from-mysite'
< input type='button' value='Click to see the data' class='get-data-from-mysite' />
--
Then in that script you do (something like):
$(function() {
$('.get-data-from-mysite').click(function() {
$('body').append("<div id='mydiv' 'style=position:absolute; z-index:999; left: ...
$('#mydiv').load(' .... // url that sends html for content
});
...etc
resize-able div stuff needs to be added too
I think the jQuery library might be what you need - specifically, look into jQuery Ajax.
Following on what Scott Evernden is explaining, you can add a <script> tag such as:
<script id="my_script_tag" type='text/javascript' src='http://mysite.com/scripts/dataget.js' />
Inside dataget.js you can simply reference the script tag itself by using its "id" (document.getElementById("my_script_tag");) and replace it (insertBefore()) with relevant data.
To get the data from your server you can use JSONP (lots of stuff on SO as well), which is an ajax technique for cross-domain communication.

Resources