how to use document.ready function on child pages - c#

i need to use JavaScript on my website. When i create new web page,which is properly work with JavaScript. When i create a new web page, which is child page, derived from master page. this page does not support my JavaScript. I use this code for auto-complete property for multiple words.
My code is here:
JavaScript code in content place holder in header
<%# Page Language="C#" MasterPageFile="~/Master_Front.master" AutoEventWireup="true"
CodeFile="Mailbox.aspx.cs" Inherits="Mailbox" Title="Mail System" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<link href="Style/ui-lightness/jquery-ui-1.8.21.custom.css"rel="stylesheet" type="text/css" />
<script src="script/jquery.min.js" type="text/javascript"></script>
<script src="script/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#txtto").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Mailbox.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#txtto").bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
</asp:Content>
C# code:
[WebMethod]
public static List<string> GetAutoCompleteData(string user_name)
{
List<string> result = new List<string>();
SqlDataReader dr=General.ReturnDR("select DISTINCT mailid from UserDetails where mailid LIKE '%"+user_name+"%'");
while (dr.Read())
{
result.Add(dr["mailid"].ToString());
}
return result;
}

You can put all script in document.ready so that the elements are ready when script acces them.
$(document).ready(function(){
//put all your script of child page here.
});

Related

Json Query not displaying correctly in MCV

I am currently trying to pass data from a controller to a view to display a pie Chart. But instead of a Pie Chart the webpage is only displaying the string as shown below. How can I get this to show the Pie Chart and not the string
Controller Code
c#
public ActionResult Index()
{
return Json(Result(), "text/plain",JsonRequestBehavior.AllowGet);
}
View Code
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=utf-8; charset = utf - 8",
cache: false,
url: '#Url.Action("Index", "Home")',
success: function (result) {
console.log(result);
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(function () {
drawChart(result);
});
}
});
});
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Marks Obtained');
var dataArray = [];
$.each(result, function (i, obj) {
dataArray.push([obj.stdName, obj.marksObtained]);
});
data.addRows(dataArray);
var columnChartOptions = {
title: "Students Performance",
width: 1000,
height: 400,
bar: { groupWidth: "20%" },
};
var columnChart = new google.visualization.PieChart(document
.getElementById('piechart_div'));
columnChart.draw(data, columnChartOptions);
}
</script>
</head>
<body>
<div id="piechart_div"></div>
The strange thing is that I downloaded an example, which works fine, and I set up a new MCV project and added the code exactly the same, but my project shows the string, while the project I downloaded will display the pie chart with no problems. I am really confused as to why this is happening

call Ajax JQuery on asp:Button OnClientClick and disable page reload if pointer goes to IF condition of Ajax JQuery

I have a asp:Button (named as "Save") in a Web Page. It has separate code for
CommandName and CommandArgument defined in a class(.cs) file, to save records.
It also has a OnClientClick event code.
HTML:
<asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Update"
OnClientClick="saveButtonClick();" CommandArgument="Save" />
Now, When I try to use OnClick event of this button, the OnClick code does
not work. I think its due to CommandName and CommandArgument or OnClientClick
code, already defined on this button but im not sure why its not working.
Since, the onClick event is not working, so I thought to write the logic of
onClick through Ajax JQuery and then I want to call this Ajax JQuery
inside pre-defined function of Javascript called onClientClick of this button.
i.e., inside saveButtonClick(); function of Javascript code
JavaScript:
<script tyep="text/javscript">
function saveButtonClick() {
//code
}
</script>
Current Ajax JQuery Code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
function saveButtonClick() {
var chk = {};
chk.requestID = $("[id*=TempGUID]").text();
alert(chk.requestID);
chk.barCode = $("[id*=txtBarcodeNumber]").val();
alert(chk.barCode);
$.ajax({
type: 'POST',
url: "IPRForm_EditCheck.aspx/CheckDuplicate",
data: '{chk: ' + JSON.stringify(chk) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
var val = data.d;
alert(val);
if (val == true) {
alert("Barcode Number already exist in system database.");
}
else {
alert("Barcode Number does not exist");
}
},
error: function (data) {
alert(data.responseText);
},
});
return false;
}
</script>
Requirement is When I click on asp:Button, it triggers the onClientClick event and go to saveButtonClick() function of Javscript, inside this function it calls the Ajax JQuery. Now, in Ajax JQuery, if pointer goes to IF condition then an alert should come and page should not reload, but if it does not goto IF condition, page should reload (as previous default behavior).
I hope I made my requirement clear to you all.
Please note that I am new in asp.net and Ajax JQuery.
Thanks in advance
function saveButtonClick() {
var chk = {};
chk.requestID = $("[id*=TempGUID]").text();
alert(chk.requestID);
chk.barCode = $("[id*=txtBarcodeNumber]").val();
alert(chk.barCode);
$.ajax({
type: 'POST',
url: "IPRForm_EditCheck.aspx/CheckDuplicate",
data: '{chk: ' + JSON.stringify(chk) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async:false,//here I am not allowing event to go further until it checks the barcode existance
success: function (data) {
var val = data.d;
alert(val);
if (val == true) {
alert("Barcode Number already exist in system database.");
return false;
}
else {
return true;
}
},
error: function (data) {
alert(data.responseText);
},
});
}
and update as following:
<asp:Button ID="yourid" UseSubmitBehavior="false"
OnClientClick="return saveButtonClick()"
runat="server" />
Explanation: See, you don't want to trigger the server side code unless bar-code not exists in the database. I have used method Preventing default behavior of button to prevent triggering server-side code. if bar-code doesn't exists than it will trigger the default behavior of the button.
Let me know if it doesn't works.
change your button code like this
<asp:Button ID="yourid" UseSubmitBehavior="false"
OnClientClick="return saveButtonClick()"
runat="server" />
JS code:
function saveButtonClick()
{
if(condition fails)
return false
else
return true
}
EDIT:3
updated JS code,At last I found that async calls cannot return a value, beacuse your code will not stop execution whether you have response from your service or not..please use this solution ,only if you like it..please keep in mind that this is a SYNCHRONOUS call ....
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
function saveButtonClick() {
var result = true;
var output = $.ajax({
type: 'POST',
url: "Default.aspx/SaveUser",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false
}).responseText;
var obj = jQuery.parseJSON(output);
if(obj.d) {
alert("Barcode Number already exist in system database.");
result = false;
}
else {
alert("entering database");
}
alert(result);
return result;
}
</script>

Using Response.Redirect in the View mvc4

I am going following steps:
in the controller action no.1 redirect to view no1;
in view no.1 I want to display cshtml page and next I want to redirect to the new action no.2 by using
#{Response.Redirect(Url.Action("CreatePdf", "Home");}
directive;
Action no.2 is reached and I've got my result (pdf file) but I can;t see the view no.1 from which I've called this action.
How can I load this view and display html page?
Just a little tweak to #DavidG's answer:
<script type="text/javascript">
$(document).ready(function () {
setTimeout(DownloadPdf, 1000);
});
function DownloadPdf() {
location.href = "#Url.Action("CreatePdf", "Home")";
}
</script>
Just tested and working. It will download the file after 1sec
A redirect causes the entire session to be directed to the new page ans loses anything you have sent out. I would use jQuery instead:
<script type="text/javascript">
$(document).ready(function () {
setTimeout(DownloadPdf, 1000);
});
function DownloadPdf() {
window.location = "#Url.Action("CreatePdf", "Home")";
}
</script>
I would suggest :
public ActionResult ControllerAction1()
{
return View();
}
For the View(), for document.ready function :
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Action2", "Controller")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'html',
data: JSON.stringify(model)
})
.success(function(result) {
// return true or false
// html of json result
})
.error(function(xhr, status) {
});
});

How to make javascript execute after using jQuery to dynamically load user control to div?

I have a Web User Control with javascript and css blocks. I'm using jQuery to dynamically load it into the main page. How do I make the alert('haha') to execute when the user control is loaded into the div called "divTable"?
In my .ascx file, I have
<script type="text/javascript">
function pageLoad(sender, args) {
alert('haha');
}
</script>
In the .aspx file, I have
<script type="text/javascript">
$(function () {
$('button').click(GetTable);
});
function GetTable() {
debugger;
var id_1 = $('#txtID1').val();
var id_2 = $('#txtID2').val();
$.ajax({
url: 'Services/Data.svc/RenderUC',
data: JSON.stringify({ path: 'Controls/ParameterizedTableControl.ascx', id1: id_1, id2: id_2 }),
type: "POST",
contentType: "application/json",
dataType: "json",
success: function (data) {
debugger;
$('#divTable').html(data);
},
error: function showError(xhr, status, exc) {
debugger;
alert('error');
}
});
}
</script>
In the .svc file, I have
[OperationContract]
public string RenderUC(string path, string id1, string id2)
{
Page pageHolder = new Page();
var viewControl = (ParameterizedTableControl)pageHolder.LoadControl(path);
viewControl.ID1= id1
viewControl.ID2 = id2;
pageHolder.Controls.Add(viewControl);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, true);
return output.ToString();
}
Any javascript that you want to run once the ajax operation is complete should go in the success handler.
function GetTable() {
debugger;
var id_1 = $('#txtID1').val();
var id_2 = $('#txtID2').val();
$.ajax({
url: 'Services/Data.svc/RenderUC',
data: JSON.stringify({ path: 'Controls/ParameterizedTableControl.ascx', id1: id_1, id2: id_2 }),
type: "POST",
contentType: "application/json",
dataType: "json",
success: function (data) {
debugger;
$('#divTable').html(data);
//
// insert whatever you want here
//
},
error: function showError(xhr, status, exc) {
debugger;
alert('error');
}
});
}
You can call your function inside your <script> block in the ascx control like this:
<script type="text/javascript">
function pageLoad(sender, args) {
alert('haha');
}
pageLoad();
</script>
This will make your script run when the browser renders your script tag.

Issue using JSON with JQuery and MVC

I'm trying to execute my controller from javascript using jquery... here is my jquery code that is executing..
<script type="text/javascript">
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(msg) {
var obj = msg.deserialize();
alert(msg);
}
});
});
</script>
Now it does execute my action..
Here is a sample of my controller class it is executing..
[AcceptVerbs(HttpVerbs.Post)]
[Url("Account/LogOn")]
public virtual ActionResult LogOn(string Username, string Password) {
if (Username == "test") {
return Json(new {
Success = true
});
} else {
return Json(new {
Success = false
});
}
}
Problem is.. when I run the method.. it just tries to download a "Logon" file which contains the result.. how do I put it back to an object in jquery so i can handle it the correct way, I've tried adding the success tag and attempt to check the msg but it doesnt even run it
Put your script inside document.ready before attempting to register any event handlers as the DOM might have not loaded yet:
<script type="text/javascript">
$(function() {
// ... copy - paste your script here
});
</script>
Also you don't need to set the dataType, jQuery knows it from the Content-Type response header from the server. Another remark: the msg object passed to the success handler is already a JSON object: you don't need to parse/deserialize it:
<script type="text/javascript">
$(function() {
$('form').submit(function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(msg) {
alert(msg.Success);
}
});
return false;
}
});
</script>
And the solution I would recommend you is to use the jquery.form plugin. Thanks to it your js code will look as easy as:
<script type="text/javascript">
$(function() {
$('form').ajaxForm(function(msg) {
alert(msg.Success);
});
});
</script>
Very neat stuff. You don't need to bother about serializing/deserializing data, preventing default events, it can even handle file uploads.
HIDDENHANCEMENT
var obj = msg.deserialize();
If that is not a joke, you would have spotted a hidden feature :)
If you're using jQuery v.1.4.x you don't need to parse a JSON string manually.
Using an older version, try
var obj = window.JSON.parse(msg);

Categories

Resources