modifying an element in master page based on action in content page - asp.net-mvc-3

I have a Link element in the Master Page. This element is initially invisible.
Upon a certain action in one of the content page, I need to make that Link element visible.
I am looking into ways of how this could be done. Can I do it from my Controller method or will I have to do it via ajax?

To manipulate the UI in mvc you need to use javascript. If your "certain action" are involved with the server I think you need to use ajax:
$.ajax({
url: "yourController/yourAction",
dataType: 'json',
success: function(json){
var domEl = document.getElementById('theIdOfyourLink');
if(json.show){
domEl.style.display = 'block';
}else{
domEl.style.display = 'none';
}
}
});
If you action are only involved with the client you can use only javascript. At the end you can playing with css to make visible or not your link:
var yourfun = function(show){
var domEl = document.getElementById('theIdOfyourLink');
if(show){
domEl.style.display = 'block';
}else{
domEl.style.display = 'none';
}
}

One option would be to use TempData or ViewData.
Your 'certain action' in your controller could be like
public ActionResult MyCertainAction()
{
TempData["ShowLink"] = true;
}
Then, you masterpage could have the following
#if (TempData["ShowLink"] != null && (bool)TempData["ShowLink"])
{
My link
}

Find control on master pages
Found this, might help.
From your code behind you can just find the control, cast it, and manipulate it.
Panel pnlWelcome2 = this.Master.FindControl("pnlWelcome") as Panel;

Related

Spring MVC Ajax updating DIV

Okay...I am coming from C# MVC using partial views/ajax, etc...
Here's what I have: 1 main page with a target ID that renders the default information using a page include.
What I want to do is onclick of a button target the original ID and render a different page as the include. Kind of like RenderPartials in C# MVC.
Can Spring (using Maven) MVC do this or is there a way to go about this that is strait forward?
Thanks,
You don't need to implement partial views just have an empty div and on click of a button make an ajax request get the content and update the div. something like below.
function button_onclick() {
var params = {}; //put parameter if any
$.ajax({
headers: {
Accept : "text/plain; charset=utf-8","Content-Type": "text/plain; charset=utf-8"},
url: "/controller",
method:"GET",
data:params,
success:function(data, textStatus,response) {
var text = response.responseText;
if (text == "") {
return;
}
$( "#DIV_ID" ).text(text);
},
error: function(response) {
alert(response);
// terminate the script
}
});
}

Ajax URL # isn't updating

I have a little problem with my script here. For some reason, it doesn't enable the #-tags and I don't know why. I created this javascript using the help of this tutorial. (The loading of the pages works well with no problems at all.)
Could someone please look it over and tell me why it doesn't work?
var default_content="";
$(document).ready(function(){ //executed after the page has loaded
checkURL(); //check if the URL has a reference to a page and load it
$('ul li a').click(function (e){ //traverse through all our navigation links..
checkURL(this.hash); //.. and assign them a new onclick event, using their own hash as a parameter (#page1 for example)
});
setInterval("checkURL()",250); //check for a change in the URL every 250 ms to detect if the history buttons have been used
});
var lasturl=""; //here we store the current URL hash
function checkURL(hash)
{
if(!hash) hash=window.location.hash; //if no parameter is provided, use the hash value from the current address
if(hash != lasturl) // if the hash value has changed
{
lasturl=hash; //update the current hash
loadPage(hash); // and load the new page
}
}
function loadPage(url) //the function that loads pages via AJAX
{
// Instead of stripping off #page, only
// strip off the # to use the rest of the URL
url=url.replace('#','');
$('#loading').css('visibility','visible'); //show the rotating gif animation
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0) //if no errors
{
$('#content').html(msg); //load the returned html into pageContet
} $('#loading').css('visibility','hidden');//and hide the rotating gif
}
});
}
You can simplify this immensely by adding a function to listen to the hashchange event, like this:
$(window).on("hashchange", function() {
loadPage(window.location.hash);
});
This way you don't need to deal with timers or overriding click events on anchors.
You also don't need to keep track of lasthash since the hashchange even will only fire when the hash changes.

Wordpress Create Category AJAX Response

I currently have a plugin that allows a user to activate/deactivate categories to drive a menu. I've created an option for the toggle and have it functioning in the create form and edit form seamlessly. The only place I can't seem to add it is to the AJAX return from wordpress when the category is created. I can create the column when the Categories page is loaded but don't know how to tap into the AJAX Return without modifying the core. Is there a hook that I'm unaware of that allows you to modify this return?
Using Akmal's answer, this is my script to check if the Taxonomy-Category was created or not.
Thanks Akmal.
Wordpress version 3.8.2
$(document).ajaxComplete(function(event, xhr, settings) {
var queryStringArr = settings.data.split('&');
if( $.inArray('action=add-tag', queryStringArr) !== -1){
var xml = xhr.responseXML;
$response = $(xml).find('term_id').text();
if($response!=""){
console.log('This is the action.');
}
}
});
Do you try to run some Javascript after ajax return (after add new category)?
Try to put below code in your code when you create the custom field in category form :
$(document).ajaxComplete(function(event, xhr, settings) {
var queryStringArr = settings.data.split('&');
if ($.inArray('action=add-tag', queryStringArr) !== -1){
your_javascript_function(); //this is your js function
}
});

Is Backbone.js suitable for getting HTML from server?

As far as I can tell, Backbone.js view represents DOM element. I take it from existing DOM or create it on the fly in el attribute.
In my case, I want to take it from server with AJAX request because I'm using Django templates and don't want to rewrite everything to JavaScript templates.
So I define el function that performs AJAX request.
el: function() {
model.fetch().success(function(response) {
return response.template
})
}
Of course, it does NOT work because AJAX request is executed asynchronous.
This means that I don't have el attribute and events does NOT work neither. Can I fix it?
Maybe the Backbone.js framework isn't the right tool for my needs? The reason I want to use that was to have some structure for the code.
P.S. I'm new to Backbone.js.
Do your ajax request from another view, or directly after the page load using jquery directly, and after you've downloaded your template, THEN instantiate your backbone view class with the proper id/el or whatever (depending on where you stored your ajax fetched template). Depending on your use-case, this may or may not be a sensible approach.
Another, perhaps more typical approach, would be to set up your view with some placeholder element (saying "loading" or whatever), then fire off the ajax, and after the updated template has been retrieved, then update your view accordingly (replace the placeholder with the actual template you requested).
When/if you update your view with new/other DOM elements, you need to call the view's delegateEvents method to rebind your events to the new elements, see:
http://backbonejs.org/#View-delegateEvents
I came across a similar requirement. In my instance, I was running asp.net and wanted to pull my templates from user controls. The first thing I would recommend is looking into Marionette because it will save you from writing a lot of boiler plate code in Backbone. The next step is to override how your templates are loaded. In this case I created a function that uses Ajax to retrieve the HTML from the server. I found an example of this function where they were using it to pull down html pages so I did a little modification so I can make MVC type requests. I can't remember where I found the idea from; otherwise, I would give the link here.
function JackTemplateLoader(params) {
if (typeof params === 'undefined') params = {};
var TEMPLATE_DIR = params.dir || '';
var file_cache = {};
function get_filename(name) {
if (name.indexOf('-') > -1) name = name.substring(0, name.indexOf('-'));
return TEMPLATE_DIR + name;
}
this.get_template = function (name) {
var template;
var file = get_filename(name);
var file_content;
var result;
if (!(file_content = file_cache[name])) {
$.ajax({
url: file,
async: false,
success: function (data) {
file_content = data; // wrap top-level templates for selection
file_cache[name] = file_content;
}
});
}
//return file_content.find('#' + name).html();
return file_content;
}
this.clear_cache = function () {
template_cache = {};
};
}
The third step would be to override Marionette's method to load templates. I did this in the app.addInitializer method. Here I am initializing my template loader and setting it's directory to a route handler. So when I want to load a template, I just set the template: "templatename" in my view and Backbone will load the template from api/ApplicationScreens/templatename. I am also overriding my template compiling to use Handlebars because ASP.net is not impressed with the <%= %> syntax.
app.JackTemplateLoader = new JackTemplateLoader({ dir: "/api/ApplicationScreens/", ext: '' });
Backbone.Marionette.TemplateCache.prototype.loadTemplate = function (name) {
if (name == undefined) {
return "";
} else {
var template = app.JackTemplateLoader.get_template(name);
return template;
}
};
// compiling
Backbone.Marionette.TemplateCache.prototype.compileTemplate = function (rawTemplate) {
var compiled = Handlebars.compile(rawTemplate);
return compiled;
};
// rendering
Backbone.Marionette.Renderer.render = function (template, data) {
var template = Marionette.TemplateCache.get(template);
return template(data);
}
Hopefully this helps. I've been working on a large dynamic website and it is coming along very nicely. I am constantly being surprised by the overall functionality and flow of using Marionette and Backbone.js.

jquery mobile ajax sends both GET and POST requests

Here is the problem:
By default jQuery Mobile is using GET requests for all links in the application, so I got this small script to remove it from each link.
$('a').each(function () {
$(this).attr("data-ajax", "false");
});
But I have a pager in which I actually want to use AJAX. The pager link uses HttpPost request for a controller action. So I commented the above jQuery code so that I can actually use AJAX.
The problem is that when I click on the link there are two requests sent out, one is HttpGet - which is the jQuery Mobile AJAX default (which I don't want), and the second one is the HttpPost that I actually want to work. When I have the above jQuery code working, AJAX is turned off completely and it just goes to the URL and reloads the window.
I am using asp.net MVC 3. Thank you
Instead of disabling AJAX-linking, you can hijack clicks on the links and decide whether or not to use $.post():
$(document).delegate('a', 'click', function (event) {
//prevent the default click behavior from occuring
event.preventDefault();
//cache this link and it's href attribute
var $this = $(this),
href = $this.attr('href');
//check to see if this link has the `ajax-post` class
if ($this.hasClass('ajax-post')) {
//split the href attribute by the question mark to get just the query string, then iterate over all the key => value pairs and add them to an object to be added to the `$.post` request
var data = {};
if (href.indexOf('?') > -1) {
var tmp = href.split('?')[1].split('&'),
itmp = [];
for (var i = 0, len = tmp.length; i < len; i++) {
itmp = tmp[i].split('=');
data.[itmp[0]] = itmp[1];
}
}
//send POST request and show loading message
$.mobile.showPageLoadingMsg();
$.post(href, data, function (serverResponse) {
//append the server response to the `body` element (assuming your server-side script is outputting the proper HTML to append to the `body` element)
$('body').append(serverResponse);
//now change to the newly added page and remove the loading message
$.mobile.changePage($('#page-id'));
$.mobile.hidePageLoadingMsg();
});
} else {
$.mobile.changePage(href);
}
});
The above code expects you to add the ajax-post class to any link you want to use the $.post() method.
On a general note, event.preventDefault() is useful to stop any other handling of an event so you can do what you want with the event. If you use event.preventDefault() you must declare event as an argument for the function it's in.
Also .each() isn't necessary in your code:
$('a').attr("data-ajax", "false");
will work just fine.
You can also turn off AJAX-linking globally by binding to the mobileinit event like this:
$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false;
});
Source: http://jquerymobile.com/demos/1.0/docs/api/globalconfig.html

Resources