Stack Exchange MiniProfiler doesn't show the profile box? - c#

I've installed the Stack Exchange MiniProfiler, and View Source shows that it is rendering the expected HTML. However it does not show the little profile detail box in the corner - what could be wrong?
<script src="/v2/Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="/v2/mini-profiler-includes.css?v=1.7.0.0">
<script type="text/javascript" src="/v2/mini-profiler-yepnope.1.0.1.js"></script>
<script type="text/javascript">
yepnope([
{ test: window.jQuery, nope: '/v2/mini-profiler-jquery.1.6.1.js' },
{ test: window.jQuery && window.jQuery.tmpl, nope: '/v2/mini-profiler-jquery.tmpl.beta1.js' },
{ load: '/v2/mini-profiler-includes.js?v=1.7.0.0',
complete: function() {
jQuery(function() {
MiniProfiler.init({
ids: ["025bbb91-9605-44b7-b33d-d8b196326dbc","2c74ce3e-8de6-4f8d-920a-e8708b22231b"],
path: '/v2/',
version: '1.7.0.0',
renderPosition: 'left',
showTrivial: false,
showChildrenTime: false,
maxTracesToShow: 15
});
});
}
}]);
</script>
And in my Global.asax.cs:
protected void Application_BeginRequest()
{
if (Request.IsLocal)
{
MiniProfiler.Start();
}
}
protected void Application_EndRequest()
{
MiniProfiler.Stop();
}
EDIT: Thanks to Sam's input I've tracked the problem to my .ajaxSetup() method. When it is commented out the profile box shows again. But I can't see why this is a problem:
$.ajaxSetup({
data: "{}",
dataFilter: function (data) {
var msg;
if (data == "") {
msg = data;
}
else if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') {
msg = JSON.parse(data);
}
else {
msg = eval('(' + data + ')');
}
if (msg.hasOwnProperty('d')) {
return msg.d;
}
else {
return msg;
}
}
});

My guess is that the global dataFilter is interfering with MiniProfiler's $.get() for jQuery Templates template files. Calling JSON.parse() on an HTML fragment will definitely throw an error.
Since you're using a recent version of jQuery, the optimized JSON parsing isn't something you need to add manually. That functionality was included in jQuery core in 1.4.
So, most simply, try changing your global dataFilter to this:
$.ajaxSetup({
data: "{}",
dataFilter: function (msg) {
if (msg.hasOwnProperty('d')) {
return msg.d;
}
else {
return msg;
}
}
});
If that doesn't fix it, you might want to look into jQuery 1.5's converters instead of the global dataFilter, which allow you to apply a dataFilter-like operation to responses of certain Content-Type. Some good examples from the guy that actually did the jQuery 1.5 AJAX rewrite here: http://encosia.com/jquery-1-5s-ajax-rewrite-and-asp-net-services-all-is-well/#comments

This sort of makes sense, perhaps your filter is mangling the results.
Adding a conditional that bypasses the filtering if you see it is a MiniProfiler JSON result should fix it.

Related

How To Use ViewBag Data In jQuery

Here I have ViewBag in a controller which contains text i.e ViewBag.Msg = "No Sprint".
And I am trying to use ViewBag.Msg in Jquery to display modal.
Now, the problem is that the script is script never gets executed.
Below is my jQuery.
<script>
$(document).ready(function () {
debugger;
if (#ViewBag.Msg != null)
{
$("#myModal").modal();
}
});
</script>
Any help will be highly appreciated. Thank You.
You need to use quotation marks for the view bag, as it will appear as a literal string.
If your debugger is not hitting at all, then you have another issue, post your full code. (your .cshtml file and layout)
<script>
$(document).ready(function () {
debugger;
if ('#ViewBag.Msg' != null)
{
$("#myModal").modal();
}
});
</script>
Please use the below code.
<script>
$(document).ready(function () {
debugger;
var msg='#ViewBag.Msg';
if (msg !== '')
{
$("#myModal").modal();
}
});
</script>

Ajax respond is not reflected into pop-up view

I have created a button to pass some parameters to a controller and get the response in a responsive pop-up.
But somehow when I click the button, nothing happens. No error in Dev.Option (F12), and I already make sure the parameter goes into my controller.
My reference : http://aspsnippets.com/Articles/Open-Show-jQuery-Dialog-Modal-Popup-after-AJAX-Call-Success.aspx
I'm using MVC C# on Visual Studio 2010. Below is my code:
My home page, all pre-requisite Jquery are already automatically reloaded inside global.asax.
HomePage.cshtml
var externalID = "123";
var susbcrNo = "456";
<a href="#COV" onclick="javascript:CustomerOneView.displayPopUpWindow(#externalID, #susbcrNo);" >DETAILS</a>
<div id="dialog" style="display: none"/>
#section Scripts{
<script type="text/javascript" src="#Url.Content("~/Scripts/CustomerOneView.js")" ></script>
<script type="text/javascript">
$("#dialog").dialog({
autoOpen: false,
modal: true,
title: "Details",
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
Inside CustomerOneView.js :
var CustomerOneView = (function () {
return {
init: function () {
},
displayPopUpWindow: function (externalID, susbcrNo) {
var postData = {
externalID: externalID,
susbcrNo: susbcrNo
};
$.ajax({
type: "POST",
url: "/Home/OneViewDetails",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$("#dialog").html(r);
$("#dialog").dialog("open");
}
});
}
};
})();
$(document).ready(function () {
CustomerOneView.init();
});
My controller :
[HttpPost]
public JsonResult OneViewDetails(string externalID, string susbcrNo)
{
Models deviceDetails = new Models();
deviceDetails.Code = externalID;
deviceDetails.Message = susbcrNo;
// call log here make sure the values.
Logger.Debug("COV called here " + externalID + " - " + susbcrNo);
// old return
// return Json(deviceDetails, JsonRequestBehavior.DenyGet);
return Json(deviceDetails);
}
My Controller is already tied into a view that supposed to be a pop-up view. Let's call it PopUp.cshtml
How can I fix this issue?
I need to clarify something about C# on the server side; if you return a value on a function/method, it will return the value to the code that called said function/method as opposed to intelligently guessing that you want to print the value back to the client so the browser may then manipulate the results?
If that is the case, you need to echo or print the return value from the function/method or from where the function/method is called.

How to call handler to post values

I have a handler StackOverFlow.cs like below:
public class StackOverFlow: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var nameValueCollection = HttpUtility.ParseQueryString(HttpUtility.UrlDecode(encodedUrl));
//..
}
}
I get QueryString parameters with ParseQueryString.
How can I test it with jquery post? Is it possible?
For example below code use a URL which ends .ashx, is it possible to use with .cs?
How can I trigger my StackOverFlow class which inherits IHttpHandler with html POST?
<script type="text/javascript">
$(function () {
//we bind the submit click function
$("#btnSubmitJSON").click(function(){
var nameValue = $("#txtName").val();
var emailValue = $("#txtEmail").val();
var contactValue = $("#txtContactNo").val();
//we just use a quick check if the value are empty or not
if(nameValue != "" && emailValue != "" && contactValue != ""){
//we can hide the button just to make sure user does not click the button during the progress.
$("#btnSubmitJSON").show();
//we can output ajax icon loading so the user know it is in progress.
$("#output").html("<img src=\"/content/images/ajax-loader.gif\" /> Please wait, we are processing your request.");
//we build the json string
var jsonData = {
'Name': nameValue,
'Email': emailValue,
'Contact': contactValue
}
//note in order to proper pass a json string, you have to use function JSON.stringfy
jsonData = JSON.stringify(jsonData);
$.ajax({
url: "/ContactHandler.ashx", //make sure the path is correct
cache: false,
type: 'POST',
data: jsonData,
success: function (response) {
//output the response from server
$("#output").html(response);
//we clean up the data
$("#txtName").val("");
$("#txtEmail").val("");
$("#txtContactNo").val("");
},
error: function (xhr, ajaxOptions, thrownError) {
$("#output").html(xhr.responseText);
$("#btnSubmitJSON").show();
}
})
}else{
$("#output").html("Please enter all fields.");
}
});
});
</script>
you need a collection of tests, an end to end test , an unit test for the javascript stubbed against a fake backend service and a unit test for the your handler, i can't give example but that is what is needed, there are lots of resources out there for unit testing C# code , javascript code and system end to end tests

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

I want to redirect from one page to another page in ASP.NET MVC 3.0 using JavaScript/jQuery/Ajax. On button click event I have written JavaScript code like below.
function foo(id)
{
$.post('/Branch/Details/' + id);
}
My controller code is like this:
public ViewResult Details(Guid id)
{
Branch branch = db.Branches.Single(b => b.Id == id);
return View(branch);
}
When I click on a button it is calling the Details action inside BranchController, but it doesn't return to the Details view.
I didn't get any error or exception. It's showing status 200 OK in Firebug. What is wrong in my code and how can I redirect to the Details view page?
You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:
$.post('/Branch/Details/' + id, function(result) {
// Do something with the result like for example inject it into
// some placeholder and update the DOM.
// This obviously assumes that your controller action returns
// a partial view otherwise you will break your markup
});
On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.
So if you only wanted to redirect the browser:
function foo(id) {
window.location.href = '/Branch/Details/' + id;
}
As a side note:
You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:
function foo(id) {
var url = '#Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
This could be done by using a hidden variable in the view and then using that variable to post from the JavaScript code.
Here is my code in the view
#Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));
Now you can use this in the JavaScript file as:
var url = $("#RedirectTo").val();
location.href = url;
It worked like a charm fro me. I hope it helps you too.
You can use:
window.location.href = '/Branch/Details/' + id;
But your Ajax code is incomplete without success or error functions.
// in the HTML code I used some razor
#Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));
// now down in the script I do this
<script type="text/javascript">
var url = $("#RedirectTo").val();
$(document).ready(function () {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Controller/Action',
success: function (result) {
if (result.UserFriendlyErrMsg === 'Some Message') {
// display a prompt
alert("Message: " + result.UserFriendlyErrMsg);
// redirect us to the new page
location.href = url;
}
$('#friendlyMsg').html(result.UserFriendlyErrMsg);
}
});
</script>
<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');
if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '#Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}
</script>
check the code below this will be helpful for you:
<script type="text/javascript">
window.opener.location.href = '#Url.Action("Action", "EventstController")', window.close();
</script>

jquery AJAX sent data in key value pair

In my aspx page, i have the js like this :-
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = "{'datakey':'hello'}"
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});
</script>
In the same webpage code behind class file ,i have the webmethod defined like this:-
[WebMethod]
public static string SendFile(string key, string data)
{
return data;
}
For some reason, i am able to get the data in the alert used on the html side. alert(msg); is giving me nothing and i am expecting to get the passed value back. In this case it should be 'Hello'.
I am missing something very small here, please help me out here.
Alter these.
The AJAX Call
$(document).ready(function () {
$("#btnLoad").click(function (evt) {
var dataForAjax = "{'datakey':'hello'}";
$.ajax({
contentType: "application/json",
data: dataForAjax,
type: "POST",
url: 'Test1.aspx/SendFile',
success: function (msg) {
var msg = msg.hasOwnProperty("d") ? msg.d : msg;
alert(msg.datakey);
}
});
evt.preventDefault();
});
});
The WebMethod
[WebMethod]
public static object SendFile(string datakey)
{
return new
{
datakey = datakey
};
}
Hope this helps.
Update:
`evt.preventDefault is for preventing postback in case your control was something like input type="submit" or asp:Button
.d is ASP.NET 3.5+ feature to prevent XSS vulnerability. ( link here )
The return type is object for the web method for automatic serialization ( link here )
Also you could omitdataType in $.ajax call but contentType is an absolute necessity ( link here )
This:
var dataForAjax = "{'datakey':'hello'}"
Should be:
var dataForAjax = {'datakey':'hello'}
AJAX does not (by default anyway) send json - it sends FORM INPUT elements! jQuery is nice and will convert javascript objects into that for you.
If you really need to you can send json, but I really doubt you do, it's rare to do that.
When you send data to method you must send apropriate key-value pairs, using object in Javascript.
Examle for you method:
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = {'key' :'datakey', 'data' : 'hello'};
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});

Categories