I am dynamically adding a jQuery multiselect control onto a page like this:
var captionCell = new HtmlTableCell { InnerHtml = control.Caption };
var inputCell = new HtmlTableCell();
inputCell.Controls.Add(inputControl);
var row = new HtmlTableRow();
row.Cells.Add(captionCell);
row.Cells.Add(inputCell);
tbl.Rows.Add(row);
And building my javascript string like this:
StringBuilder sb = new StringBuilder();
sb.AppendLine("<script type=\"text/javascript\">");
sb.AppendLine("var $callback = $(\"#callback\");");
sb.AppendLine("$(document).ready(function () {");
sb.Append("$(\"#");
sb.Append(multiSelectControl.ClientID);
sb.AppendLine("\").multiselect(");
sb.AppendLine("{");
sb.AppendLine("show: \"fade\",");
sb.AppendLine("hide: \"fade\",");
sb.AppendLine("click: function (event, ui){");
sb.AppendLine("$callback.text(ui.text + ' ' + (ui.checked ? 'checked' : 'unchecked'));");
sb.AppendLine("},");
sb.AppendLine("});");
sb.AppendLine("});");
sb.AppendLine("</script>");
Then adding the script to the page like this:
ScriptManager.RegisterClientScriptBlock(this.Page, Page.GetType(), "CreateControl" + inputControl.ClientID,
sb.ToString(), false);
But im getting the following error when trying to do this:
Microsoft JScript runtime error: Object doesn't support this property or method
Please assist guys.
Thanks in advance.
You need to have jQuery included in the page to use document.ready, You did not add the script tag to include jquery in the page, Add script tag to include jquery.
<script type="text/javascript" src="/jQueryFolder/jquery.js"></script>
var $callback = $("#callback");
$(document).ready(function() {
$("#ClientID").multiselect({
show: "fade",
hide: "fade",
click: function(event, ui) {
$callback.text(ui.text + ' ' + (ui.checked ? 'checked' : 'unchecked'));
}
});
});
I solved this by creating a user control, and when I need to use the script above I just loaded the user control.
Solved everything and works really well.
Related
I currently have the following code that display a jquery growl when the page loads.
<script>
window.onload = function () {
var msg = "My alert message";
jQuery.jGrowl(msg, { life: 5000, theme: 'redgrowl' });
}
</script>
I would like to be able to call a jquery growl function from codebehind, I use a scriptmanager but have so far not been able to get it to work. I have tried this..
var sb = new StringBuilder();
sb.Append(" window.onload = function () {");
sb.Append(" var msg = \"Hello world\";");
sb.Append(" jQuery.jGrowl(msg, { life: 5000, theme: 'redgrowl' });");
sb.Append(" }");
ScriptManager.RegisterStartupScript(this, GetType(), "jgrowlwarn", sb.ToString(), true);
But that does not show anything at all. I have the current code that load on window.onload on the bottom of my page just before end of body, and the jquery.growl.js is in the head tag. What could be wrong?
I have written the script dynamically using string builder as follows
public static void ShowMessage1(ENUM_MessageType pMessageType, string pMessage, Button c)
{
StringBuilder strScript = new StringBuilder();
strScript.Append("<script type=\"text/javascript\" src=\"").Append("/Scripts/jquery-1.4.1.js").Append("\"></script>");
strScript.Append("<script type=\"text/javascript\" src=\"").Append("/Scripts/jquery.msgBox.js").Append("\"></script>");
strScript.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"").Append("/Styles/msgBoxLight.css").Append("\" />");
strScript.Append("<script type=\"text/javascript\">");
strScript.Append("(function example()");
strScript.Append("{");
strScript.Append("$.msgBox({");
strScript.Append("title:'" + lMessageType + "'");
strScript.Append(",");
strScript.Append("content:'" + pMessage + "'");
strScript.Append(",");
strScript.Append("type:'" + lOptionType + "'");
strScript.Append(",");
strScript.Append("buttons: [{ value: 'Yes' }, { value: 'No'}],");
strScript.Append("success: function (result) {");
strScript.Append("if(result == 'Yes'){");
strScript.Append("javascript:_doPostBack('" + c.ClientID + "','');");
strScript.Append("}");
strScript.Append("}");
strScript.Append("});");
strScript.Append("})();");
strScript.Append("</script>");
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(enumClass), "info", strScript.ToString());
}
}
I am getting the exception as ReferenceError: _doPostBack is not defined can some one help me
Its should javascript currently you have
strScript.Append("avascript:_doPostBack('" + c.ClientID + "','');");
It should be:
strScript.Append("javascript:__doPostBack('" + c.ClientID + "','');");
Missing j in front. Also make sure that its __ not a single underscore.
Looks like you're missing an underscore on your __doPostBack() call.
Also, take a look at the success in your rendered JS:
(function example() {
$.msgBox({
title : 'INFORMATION',
content : 'I am from client side',
type : 'confirm',
buttons : [{
value : 'Yes'
}, {
value : 'No'
}
],
success : function (result) {
if (result == 'Yes') {
javascript : __doPostBack('Button1', ''); // <--- this line
}
}
});
})();
If you are just trying to call a postback there, get rid of the javascript : so that it reads like this:
strScript.Append("__doPostBack('" + c.ClientID + "','');");
Also, according to the answer on this SO question, make sure there is an ASP.NET WebControl rendered to the page. __doPostBack() is automatically included on the page when a WebControl is rendered. So, if you on't have one on the page, there's a chance that the __doPostBack() method could be missing.
If you don’t have any asp.net server side postback controls on the page the “_doPostBack not defined” error will be thrown on the client. To avoid the described error you can try adding following lines of code into the page load event:
protected override void OnPreLoad(EventArgs e)
{
this.Page.ClientScript.GetPostBackEventReference(this, string.Empty);
base.OnPreLoad(e);
}
The GetPostBackEventReference returns a string that can be used in a client event to cause postback to the server
The other approach is to add hidden asp:Button which will register the same scripts as GetPostBackEventReference method.
i am working on a project in c#.net , I have a jquery code in my master page and the master page is included in my home page. I have created hyperlinks dynamically in my home page.
i want that when ever a user clicks on the hyperlink, instead of the wholepage only 1 part of the page with div class=refresh1 will reload.
i have include following jquery in my head tag.
<script type="text/javascript">
$(document).ready(function () {
$("a").click(function () {
var link1 = $(".mylink").text();
$.post("loaddata.aspx",
{
link: link1
},
function (responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
alert("Done!");
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
$(".refresh1").load('loaddata.aspx .part1');
});
});
});
</script>
here mylink is class of 'a' tag.
i want that when ever the hyperlink will be clicked it will load the refresh1 class part from another page i.e from loaddata.aspx with class=part1.
in loaddata.aspx i want to retrive the value of link that i have passed in post method .how can i do it plzzzzzzzzz reply aasap.
You can use .load() like so:
$('a').click(function () {
var link1 = $(this).text();
$(".refresh1").load('loaddata.aspx .part1',{
link : link1
},function(data){
//optional callback code
});
});
the .load() fires a GET request though. To do it using POST, you must use .post() and parse the data it retrieves:
$('a').click(function () {
var link1 = $(this).text();
$.post('loaddata.aspx',{
link : link1
},function(data){
$(data).find('.part1').appendTo('.refresh1');
});
});
You can use Request["link"] to get the value.
Also make sure you decode the value after you retrieve.
I am working on asp.net c# . I want to add javascript function in c# by using htmlgeneric control .I have used code ,
HtmlGenericControl scriptTagLinks = new HtmlGenericControl("script");
scriptTagLinks.Attributes["type"] = "text/javascript";
string scrip = "$(function () {$([src='" + url + "']" + ").pinit();});";
// txtDesc.Text = rdr.GetString(4);
// TxtLink.Text = rdr.GetString(6);
scriptTagLinks.Attributes["src"] = scrip;
this.Controls.Add(scriptTagLinks);
But i should get like this ,
<script type="text/javascript">
$(function () {
$("[src='/pinterest/portals/0/Images/about-person3.jpg']").pinit();
$("[src='/pinterest/portals/0/Images/about-us-group.jpg']").pinit();
});
</script>
But i am getting this as
<script src="$(function () {$([src='/pinterest/portals/0/Images/about-us-group.jpg']).pinit();});" type="text/javascript">
How can i add $([src='/pinterest/portals/0/Images/about-us-group.jpg']).pinit();}); between tags .
My attempted methods.
Looking at the JS via browser, the #ViewBag.CC is just blank... (missing)
var c = "#" + "#ViewBag.CC";
var d = $("#" + "#ViewBag.CC").value;
var e = $("#" + "#ViewBag.CC").val();
var c = "#ViewBag.CC";
var d = $("#ViewBag.CC").value;
var e = $("#ViewBag.CC").val();
if you are using razor engine template then do the following
in your view write :
<script> var myJsVariable = '#ViewBag.MyVariable' </script>
UPDATE:
A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```
<head>
<script>
var AppConfig = #Html.Raw(Json.Encode(new {
baseUrl: Url.Content("~"),
fbApi: "get it from db",
awsUrl: "get it from db"
}));
</script>
</head>
And you can use it in your JavaScript code as follow:
<script>
myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
alert(myProduct.fullUrl);
</script>
try: var cc = #Html.Raw(Json.Encode(ViewBag.CC)
<script type="text/javascript">
$(document).ready(function() {
showWarning('#ViewBag.Message');
});
</script>
You can use ViewBag.PropertyName in javascript like this.
ViewBag is server side code.
Javascript is client side code.
You can't really connect them.
You can do something like this:
var x = $('#' + '#(ViewBag.CC)').val();
But it will get parsed on the server, so you didn't really connect them.
You can achieve the solution, by doing this:
JavaScript:
var myValue = document.getElementById("#(ViewBag.CC)").value;
or if you want to use jQuery, then:
jQuery
var myValue = $('#' + '#(ViewBag.CC)').val();
None of the existing solutions worked for me. Here's another solution I found that did work:
Controller:
TempData["SuccessMessage"] = "your message here";
View:
let msg = '#TempData["SuccessMessage"]';
Try this:
Anywhere in HTML: <input hidden value=#ViewBag.CC id="CC_id" />
In JS: var CC= document.getElementById("CC_id").value.toString();