Sorry I'm very new to JQuery... I can't for the life of me figure out where my bug is. When I run this I don't get any results. When I check the error in Firefox and Chrome it points to the source line. I just can't see anything wrong.
Here's my script
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#CustName').autocomplete({
//Firefox points to a syntax error here
source: #SqlHelper.getJSONArray("CustName", "dba.BillingInfo")
});
});
</script>
<p>Customer Name #Html.TextBox("CustName")</p>
SqlHelper.getJsonArray is a method I'm using to return a JSON string. I've checked and double checked that it is in fact returning valid JSON.
public static string getJSONArray(string column,string table)
{
string qry = "SELECT DISTINCT " + column
+ " FROM " + table
+ " WHERE " + column + " is not null"
+ " AND " + column + " <> ''"
+ " ORDER BY 1";
List<string> result = new List<string>();
SqlDataReader reader = execQry(qry);
while (reader.Read())
{
result.Add(reader[0].ToString());
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(result);
}
[UPDATE]
Here is the syntax error firefox is spitting back:
source: $.parseJSON(["Customer1","Customer2...
---------------------^
So I'm beginning to think the issue is the quotes are getting rendered as quot; instead of ". If I try putting my source as ["Test1","Test2","Test3"] it works fine. Is there a way to get razor to not HTML encode the string?
[UPDATE]
That was the issue. The solution was using Html.Raw()
The issue was razor automatically HTML encoding the JSON. The fix is using HTML.Raw
$('#CustName').autocomplete({
source: #Html.Raw(SqlHelper.getJSONArray("CustName", "dba.BillingInfo"))
});
Try using $.parseJSON.
$(document).ready(function () {
$('#CustName').autocomplete({
//Firefox points to a syntax error here
source: $.parseJSON(#SqlHelper.getJSONArray("CustName", "dba.BillingInfo"))
});
});
Related
I have an application where I am getting some value over ajax post method and sending to [WebMethod] static method code behind. But I cannot assign the value to the textbox of the page. Here is my code:
[WebMethod]
public static string copyData(string name, string msg, string sing_cal1, string timepick, string timepickst, string sing_cal4, string step)
{
if (step == "3")
{
if (HttpContext.Current != null)
{
Page page = (Page)HttpContext.Current.Handler;
TextBox txtCampaignNameEditC = (TextBox)page.FindControl("txtCampaignNameEdit");
TextBox txtMsgEditC = (TextBox)page.FindControl("txtMsgEdit");
TextBox txtSentFromC = (TextBox)page.FindControl("txtSentFrom");
Label lblScheduledTimeC = (Label)page.FindControl("lblScheduledTime");
txtCampaignNameEditC.Text = name; // Here I am getting error as "Object reference not set to an instance of an object."
}
}
return "";
}
<script type="text/javascript">
$(document).ready(function () {
$('#wizard').smartWizard({ onLeaveStep: leaveAStepCallback, onFinish: onFinishCallback });
function leaveAStepCallback(obj) {
var step_num= obj.attr('rel');
var name = $("#<%= txtCampaignName.ClientID %>").val();
var msg = $("#<%= txtMessage.ClientID %>").val();
var cal1 = $("#<%= single_cal1.ClientID %>").val();
var timepicks = $("#<%= txtTimePick.ClientID %>").val();
var pickst = $("#<%= txtTimePickST.ClientID %>").val();
var cal4 = $("#<%= single_cal4.ClientID %>").val();
$.ajax({
type: "POST",
url: "CreateCampaign.aspx/copyData",
data: '{name: "' + name + '", msg: "' + msg + '", sing_cal1: "' + cal1 + '", timepick: "' + timepicks + '", timepickst: "' + pickst + '", sing_cal4: "' + cal4 + '", step: "'+ step_num +'"}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
return true;
}
This code behind method does not let me to assign the received parameter to the textbox. Please help me on this. Thanks.
The only time the code behind has access to modify controls is during the page life cycle. Once the page has been rendered the page is no longer connected to the server.
Moving code that references controls from the WebMethod to another function will not work because there are no controls. You must return data from the web method and place the data in the DOM using JavaScript.
To be more clear, I will say that you can't assign values to textbox using [WebMethod], because [WebMethod] don't run the ASP.Net page lifecycle. You need to use JavaScript to assign values to a textbox.
For tutorials on how to get and set textbox values with JavaScript you can check: this or this
Set the ClientIDMode property of the textbox to Static. That will ensure that whatever ID you set for the textbox will also be the id on the client. That way the id will be predictable and you can refer to it from JavaScript.
Then in your client code after the ajax is executed you can update the value in JavaScript.
document.getElementById("yourControlId").value = "whatever";
I am generating html through C#
myStr = "<span class='red'>September 1980</span><br /><div>abcdef\nhijklm</div>";
shtml = "<span class='red' title='<pre>" + HttpUtility.JavaScriptStringEncode(myStr, false) + "</pre>' id='" + jc.FirstOrDefault().UserId + "'>" + content + "</span>" + after;
... snip snip ...
<%= shtml %>
And my jquery script for initializing qtip is:
$('[title!=""]').each(function(){
$(this).qtip({
hide: {
fixed: true, delay: 300
}, show: 'mouseover',
position: {
my: 'top center',
at: 'bottom center',
viewport: $(window),
adjust: {
method: 'shift shift'
, screen: true
}
}, style: {
classes: 'qtip-light', // Inherit from preset style
tip: 'topCenter'
}
});
});
Now the tooltip is showing:
\u003cspan class=\u0027abcd\u0027 title=\u0027September 05, 2013 12:06\u0027\u003e\u003ci
How can I render the html in tooltip?
this has been eating my time and brains... please help!
Note: please read the following before marking this question as duplicate:
I searched all the related posts, but none of the soutions worked for me. My use case is different as I am using qtip to show the string generated by javascriptstringencode.
I could not find any built in function to decode the data which is encoded using HttpUtility.JavaScriptStringEncode. So I created a JS function after some research in various sites.
String.prototype.replaceAll = function(str1, str2, ignore) {
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof(str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);
}
function decodeJs(encodedString) {
var decodedString = encodedString;
decodedString = decodedString.replaceAll("\\u0026", "&");
decodedString = decodedString.replaceAll("\\u0027", "\'");
decodedString = decodedString.replaceAll("\\u003c", "<");
decodedString = decodedString.replaceAll("\\u003e", ">");
return decodedString;
}
function replaceText() {
$("*").each(function() {
if (!$(this).children().length) {
$(this).text(decodeJs($(this).text())).val(decodeJs($(this).val()));
}
});
}
$(document).ready(replaceText);
$("html").ajaxStop(replaceText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I try to add the following javascript code.
<script>
#if (ViewBag.checkedArtikel != null)
{
foreach (int ac in ViewBag.checkedArtikel)
{
String temp = "'#addartikel" + ac + "'";
<text> $(#temp).toggleClass('down');</text>
}
}
</script>
If i leave out the script tag i get the right jquery commands:
$('#addartikel1').toggleClass('down');
But with the script tag i get this error:
Uncaught SyntaxError: Unexpected token &
You have very badly mixed server side Razor code with client side javascript. Here's the correct way to do that, by using a JSON serializer:
<script type="text/javascript">
var articles = #Html.Raw(Json.Encode(ViewBag.checkedArtikel ?? new int[0]));
$(articles).each(function() {
$('#addartikel' + this).toggleClass('down');
});
</script>
Use this code:
<text>$(#Html.Raw(temp)).toggleClass('down');</text>
Or you can use your old code without adding quotes to variable:
String temp = "#addartikel" + ac;
<text> $('#temp').toggleClass('down');</text>
I have a link like that. It's getting from instagram api.
http://localhost:60785/access_token.aspx/#access_token=43667613.4a1ee8c.791949d8f78b472d8136fcdaa706875b
How can I get this link from codebehind?
I can take it with js but i can't get it after assign to label. I mean:
<script>
function getURL(){
document.getElementById('lblAccessToken').innerText = location.href;
}
</script>
This js function is in body onload event. How can I reach this innerText value from codebehind?
If you are using ASP.NET 4.0 and jQuery, its fairly easy. Otherwise you may have to deal with mangled id and have to deal with DOMReady on your own. Try this
Markup
<asp:Label ID="lblAccessToken" runat="server" ClientIDMode="Static"></asp:Label>
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myToken = GetHashParameterByName("access_token");
$("#lblAccessToken").html( myToken );
});
function GetHashParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)')
.exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
You want the value on Page_Load right? I haven't figured out a way myself to fetch the hash value on Page_Load.I usually do one of these things
Pass the hash value to a jQuery ajax method and store it there.
Grab the hash value and redirect to the same page after converting it to a querystring
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myToken = GetHashParameterByName("access_token") || "";
if(my_token !=== ""){
window.location = window.location.split("/#")[0] + "?access_token=" + myToken;
}
});
function GetHashParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)')
.exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
Now at Page_Load, grab it like
string token = Request.QueryString["access_token"];
Please note that it takes one more round trip to the server and so not very efficient. But this is what I do.
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();