Tilbake til hovedsiden

WebSeo analyse – Bedrifts Webdesign – IT support – Optimalisering

Finn webside relaterte utrykk og ord

reklame

 

Nettsiden din ligger ute i ørkenet et sted og er en oase med masse vann.

En tørst bortkommen mann vandrer rundt i ørkenet under stekende sol og er desperat for noe å drikke.

Hadde han bare visst hvilken retning din oase lå…

Hvis det var skilter spredt ut rundt omkring i ørkenet med reklame for din oase, med distanse og retning, ville dette øke sjansen for å få besøk av denne mannen og andre som ham.

Hvis ikke Google vet hva din side handler om og hvor den ligger, vil den mest sannsynligvis ikke sende besøkende i din retning. La oss hjelpe deg med å presentere din side til internett, slik at søkemotorer forstår innholdet, indekserer disse og velger heller å presentere deg til søkere ovenfor dine konkurrenter.

Hva skal til for å få bedre plassering i søkemotorer?

Som de aller fleste har fått med seg er organiske søkposisjoner et av de viktigste besøkskildene til bedriftssider.

Ved å ha innholdsrik og nyttig informasjon om dine tjenester økes sjansen til å vises som søkresultat. Det holder ikke lenger med korte setninger og et bilde for å kunne komme på første siden. Det er videre veldig viktig med informasjonsveiledning til søkemotorer kalt rich snippets. Disse er koder som forklarer til søkemotorer bl.a. hva siden handler om (Artikkel, Blogposting osv.), hvor den ligger og andre tilleggsinformasjon.

blue-up-arrows (469x227)
Bedre plassering Google

 

 

 

 

 

 

 

 

 

 

 

Så hvem får 1. plassen?

Det korte svaret er: Den som gir mest relevant informasjon til søket som er utført.

Bilder og helhet vil være viktig, og videre vil tilbakelinker og interne linker veie opp.

Forskjellige ord har forskjellige vanskelighetsgrader til plassering, ut i fra konkurranse og likhet med andre.

Desto flere søkere som klikker på din side, jo høyere er sjansen for å rykke opp i posisjon. Det vil altså være viktig å ha fristende og svarende

informasjon til søket.

 

Hva er sitelinks – Flere linker ved søk

Hvis første posisjonen er totalt dominert av en side, altså ingen andre er i nærheten til innholdskvalitet, får man mulighet til å

få noe som heter SITELINKS.

Sitelinks er markering av flere resultater fra samme webside og kan presentere alt fra 2 til 10 ekstra resultater ved søk.

Det vil i praksis si at man får maksimalt de første 10 resultatene og klikkfrekvens øker med opptil 70%!

Hvis søkeboks meta er riktig innført, får man ved 10 sitelinks mulighet til å få søkeboks vist i Google.

 

 

La din Nettside gjøre promoteringen!

I dag er nettsiden til bedriften den viktigste presentasjonen av deres tjenester, produkter og informasjon. En målrettet hjemmeside gir besøkende informasjonen som søkes, raskt og enkelt. Det hjelper lite med websider som ser visuelt fantastisk ut, når informasjonen er umulig å finne fram til av bruker og søkemotorer.

flat,550x550,075,f

Printed poster with SEO sign and tags on social engine optimization theme. Added a slightly vignetting, and toning on the image. Close up shot.

Printed poster with SEO sign and tags on social engine optimization theme. Added a slightly vignetting, and toning on the image. Close up shot.

Vi er et av Norges mest SEO fokuserte webdesignbyrå, som ikke bare forstår hvordan søkemoterer som Google, Yahoo, Bing fungererer, men implementer elementer for bedre synlighet i alle våre pakker. Vi hjelper daglig våre kunder med oppgradering av deres sider, feilsøking og utbedring og hjelper dem med å bli mer synlige.

Vårt webdesign avdeling i Oslo ligger sentralt i Oslo.

INSTALLERE WORDPRESS GUIDE – LAG DIN HJEMMESIDE SELV

Du har flere muligheter og valg når du skal lage din egen webside. Valgene står mellom html5 og css3 eller en cms sytem som står for content management system. WordPress er den mest kjente av disse, etterfulgt av joomla og drupal.
Computer-3 (338x230)
Det finnes også cms systemer til webshop og disse er magento, prestashop i tillegg til ecommerce addon til wordpress som er woocommerce og virtuamart til joomla. Det finnes en god del andre ecommerce tillegg til alle 3 cms systemene nevnt over, men her gjelder det å velge de best utviklede for sikkerhet og funksjonell stabilitet.

Magento og prestashop er i sine egne verdener når det gjelder læremønster, hvor bruk av allerede eksisterende system er såvidt lett å lære mens installasjon kan være nær umulig for nybegynere. Disse er derimot meget godt sikret og kan ha millioner av produkter.

Installasjon av wordpress
Det er flere og flere domenehoster som tilbyr 1 klikk installasjon av wordpress. One.com og webhuset er 2 leverandører vi kan nevne.

Du trenger en database til å lagre innstillinger og brukere på wordpress, mens datafiler lagres på FTP(File transfer protocol) Vi vil oppdatere denne artikkelen med full installasjonsguide til database installasjon.
Etter fullførelse, valg av brukernavn og passord, logger du inn på wordpress systemet. WordPress kommer med 2 versjoner av velkjente twenty fourteen, twenty fifteen og twenty sixteen temaer.
Det finnes mange gratis og betalte tems som kan installeres fra utvidelser og mange av disse har en veiledning eller oppsett slik at du kan endre utsende og funksjoner.
Det er også allerde lagt opp hello-world post, som man gjerne sletter snarest.
Her er en lett oversikt over hvordan wordpress fungerer:

Sider i wordpress er enten page eller post format. Det finnes kategori og tag/stikkord arkiv funksjon som gir deg mulighet til å spesifisere hva sideinnholdet er. Stikkord er reservert poster, men kan aktiveres for page sider med plugin eller endring av tema kildekode.

Før vi glemmer hva forskjellen på post og page er kan vi si at forskjellen er at Page er ment til å være av tyngre natur som bl.a. om oss sider, hovedsider, kontaktskjema sider og hovedsider generelt. Poster er ment til å være av lettere og kortere innhold som oppdateringer og kortere artikler.

Nå skal vi fortelle deg litt mer om plugins(utvidelser) som er grunnen til ay wordpress er en av verdens mest avanserte cms systemer. Plugins er koder som endrer funskjoner og i mange tilfeller legger til funskjoner.
Noen eksempler er Seo managers dom hjelper deg med å gjøre din side mer søkervennlig, backup Plugins som hjelper deg med manuell og automatisk autobackup, slik at du kan gjenopprette en wordpress side som har blitt hacked eller sluttet å fungere. Mange Plugins gir deg mulighet til å kun påvirke post eller pages, noe som gir deg mange muligheter til å skille disse to fra hverandre.

 

For å nevne flere plugin kan vi ta med Google maps implementering og stjerne rating systemer, slidere som kan vise meget fangende bilde presentasjoner.

hvordan få stjerner på Google og Bing

En annen funskjon på wordpress er kalt shortcodes. Disse er koder som kan opprettes av de med god kodeforståelse eller plugins. formatey er oftest [jegerenkode].

Hvis koden er gyldig kan du bruke shortkoden og worpress vil automatisk overtte denne til funskjonen som den skal utføre. En eksemle vil være google maps kortkode som kommer til å innholde info om lokasjon. En slik kode vil se ca. slik ut [googleplugin-2255115552,225555855] og vil vise kordinatene på google maps. En kontaktskjema kan se ut som [contctformplugin-5] og vil vise kontakt skjema som du har laget i pluginet som denne tilhører. Shorcodes kan være litt vanskelig å forstå i begynnelsen, men er en absolutt gave når du forstår potensialet.

Det er en ting å sette opp en velfungerende wordpress side der alt ser ut som det skal og at siden er brukervennlig. Vi på IASC webdesign har mange kunder som bestiller oppsett og utvikling av tilpasset side som fungerer optimalt og kunden kan konsentrere seg om å lage nytt innhold.

Instruks på installering av tilleggsmoduler\plugins til WordPress

I denne artikkelen skal vi se litt nærmere på hvordan du installerer utvidelse i form av plugins i wordpress. Det finnes 2 måter å installere en utvidelse, første er via utvidelser/legg til som åpner wordpress arkiv. Her søker du etter ønsket plugin, for eks. backup, og velger ønsket plugin og velger installer. Etter installsjon får du mulighet til å aktivere den nyinstallerte utvidelsen med en gang eller avvente. Da ikke alle utvidelser vises i wordpress repertoaret enter fordi utvikler ikke er registrert utvidelsen eller at dens funksjoner er i strid med wp regelverk eller ikke godkjent.

Hvordan installere wordpress plugin

Det er selvfølgelig en god ide å sjekke grundig om du kan stole på utvikleren/pluginnavnet i form av omtaler og artikler.
Når du har forsikret deg om at du ønsker å fortsette med installsjon, trenger du koble deg til din wordpress installsjon via FTP.
Plugin pleier å være pakket inn på zip eller rar format og denne inneholder en mappe som er pluginet selv. Denne mappen skal øverføres til wp-installasjonsmappe/wp-content/plugins/

Etter overføring går du til utvidelsepanelet på wordpress, finner navnet og aktivere denne.

Ajax Extender for Identifying External Links

Author: Fredrik Kalseth

An entry about asp.net | ajax Publication date 4. April 2007 20:46

.NET slave Mads Kristensen wrote a nice post on how to identify external links using JavaScript a few days ago, over on his blog. I had been meaning to implement something similar here, and his post gave me the much needed nudge in the rigth direction – as you can see from the nice little icon next to the link to his post – but this link, which is local, does not have it. Awesome :)

I decided to take the idea a bit further than simply embedding a javascript into my pages, and implemented it as an ASP.NET Ajax ControlExtender instead. The control, which I’ve called ExternalHyperLinkExtender, has the following properties to configure it:

ExternalLinkCssClass
Lets you specify the CSS class that should be applied to external links. Typically, this will be a class that looks something like this:

.ExternalLink 
{
background: url(Icons/ExternalLinkIcon.png) right top no-repeat;
padding-right: 9px;
}

LocalHyperLinkRegex
Lets you specify a regular expression pattern that the extender will then use to identify local links – any link that does not match the pattern will get the ExternalLinkCssClass applied to it. If you do not specify this property, the extender will attempt to determine if the link is external by doing a string compare with the path of the document it is on instead (much like Mads original script does).

AddTargetIfNotSet
If you set this to true, the extender will set the target attribute of the hyperlink to ‘_blank’, if it has not already been set.

A usage example then, would look something like this (taken from the code that renders the very text you are reading now):

<asp:Label
    ID="_text"
    runat="server"
    Text='<%# Eval("Text") %>' />
<iridescence:ExternalHyperLinkExtender
    ID="_textExtender"
    runat="server"
    AddTargetIfNotSet="true"
    LocalHyperLinkRegex="^http://blog\.iridescence\.no"
    ExternalLinkCssClass="ExternalLink"
    TargetControlID="_text" />

I wont go into the details of how to write an ASP.NET Ajax ControlExtender – you’ll find a good walkthrough covering that over at the official ASP.NET site, but below is the javascript code that is the heart of the extender:

initialize : function() 
{
Iridescence.Ajax.ExternalHyperLinkBehavior.callBaseMethod(this, 'initialize');
// get the element we're extending
    var element = this.get_element();
// get all the anchors that are children of the element
    var links = element.getElementsByTagName('a');
for(var index in links)
{
// for each anchor, find any that link off-site
        var link = links[index];     
if(link.href && link.innerHTML && link.innerHTML.length > 0)
{       
var externalLinkFound = false;
if(this._LocalHyperLinkRegex != null && this._LocalHyperLinkRegex.length > 0)
{            
// use regex to test
                var regex = new RegExp(this._LocalHyperLinkRegex);                
externalLinkFound = !link.href.match(regex);                
}
else            
{
// do a simple string comparison to test
                externalLinkFound = !link.href.startsWith(document.location.href.substring(0, 13));
}
// if we found an external link...
            if(externalLinkFound)
{
if(this._AddTargetIfNotSet && !link.target)
{
// ...set target 
                    link.target = '_blank';     
}
if(this._ExternalLinkCssClass)
{
// ...add css class
                    link.className += " " + this._ExternalLinkCssClass;
}
}                                
}
}   
}

Finally, I’ll leave you with this little nugget of sexyness: When all the major browsers (come on, IE team!) gets CSS3 support, we could solve this in a much more elegant way by using the CSS3 Selectors, as described in this post. Now that looks awesome :)

 

Update 17/6 2007

So I finally got around to fixing the bug that prevented this from working in IE6 – basically IE6 always returned ‘undefined’ for link.text, causing my script to skip all links. I’ve changed it to link.innerHTML now :)

Be the first to rate this post

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

4/24/2007 7:33:11 AM

Fredrik

Seems to be a bug in my code that prevents this from working in IE7, oops! I’ll get around to fixing it in a few days – or you could just go get Firefox 😉

Fredrik

A Context Menu Control Extender

Author: Fredrik Kalseth

An entry about asp.net | ajax | javascript Publication date 4. August 2007 13:19

One of the things I’ve been missing in the Ajax Control Toolkit, is a context menu extender – so I figured I’d write one myself :) Turns out it was much easier than I anticipated, and after about an hour or so I had something that works fairly well. Basically, it allows you to do something like this:

<asp:Panel
    ID="_context"
    runat="server"
    Style="background-color:#cecece; width:250px; height:250px">            
Context area            
</asp:Panel>
<asp:Panel
    ID="_menu"
    runat="server" 
Style="border:solid 1px black; background-color:White; padding:4px;">
    My Context menu!
</asp:Panel>
<iridescence:ContextMenuExtender
    ID="_cmExt"
    runat="server"
    TargetControlID="_context"
    ContextMenuControlID="_menu" /> 

The extender will then make the TargetControl float wherever the mouse is located when you right-click anywhere inside the configured ContextMenuControl.

You can get the source code at the bottom of this post – below I’ll just go through the javascript code that makes it work. As I said before when talking about control extenders, I will assume that you know how to write them – if you don’t, check out this tutorial for a better introduction than one I could include here :)

To hook things up, we override the initialize function:

initialize : function() 
{
Iridescence.Ajax.ContextMenuBehavior.callBaseMethod(this, 'initialize');
this._contextElement = this.get_element();
this._menuElement = $get(this._contextMenuControlID);
// style the context menu
    this._menuElement.style.display = 'none';
this._menuElement.style.position = 'absolute';
// attach event handlers
    this._onMouseDownHandler = Function.createDelegate(this, this._onMouseDown);
this._onDocumentContextMenuHandler = Function.createDelegate(this, this._onDocumentContextMenu);
this._onDocumentClickHandler = Function.createDelegate(this, this._onDocumentClick);
$addHandler(this._contextElement, 'mousedown', this._onMouseDownHandler);  
$addHandler(document, 'contextmenu', this._onDocumentContextMenuHandler);   
$addHandler(document, 'click', this._onDocumentClickHandler);
}

Here we simply get references to the Target and ContextMenuControls, and then add handlers for the events that we need.

First of all, we need to capture the mousedown event of the context area, so that we may show the context menu when the user right clicks inside it. This is handled by the _onMouseDown method:

_onMouseDown : function(e)    
{                
if (e.button == 2)
{                   
// calculate current mouse position            
        var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop; 
var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft; 
// and move context menu there
        this.__menuElement.style.left = e.clientX + scrollLeft + 'px';
this.__menuElement.style.top = e.clientY + scrollTop + 'px';
this.__menuElement.style.display = '';
// set flags
        this._menuVisible = true;
this._menuJustShown = true;            
}
}

This method checks whether the right mouse button was clicked, and if so we need to figure out the current mouse position (offset by the scroll position), and position the context menu element accordingly, before showing it.

Normally, a right click would cause the browsers context menu to be displayed; we dont want that, as it would hide our custom context menu. Thus we’ve also hooked up to the contextmenu event of the document element, which is handled by the _onDocumentContextMenu method:

_onDocumentContextMenu : function(e)
{        
if(this._menuJustShown)
{
// when our custom context menu is showing, we want to disable the browser context menu
        e.preventDefault();
this._menuJustShown = false;
}
else if(this._menuVisible)
{        
// user right-clicks anywhere while our custom context menu is visible; hide it
        this._hideMenu();
}
}

Here, if our custom context menu was just shown, we prevent the browsers context menu from displaying by calling the preventDefault() method on the event arguments object.

The last functionality we need, is to be able to hide the context menu when the user clicks anwhere outside it after it has been shown. Above, we’ve solved that for when the user right-clicks – we also need to include a left-click solution. We do this by handling the click event of the document element, which is handled by the _onDocumentClick method:

_onDocumentClick : function(e)
{                                   
if(this._menuVisible && e.button != 2)
{
// user left-clicked anywhere while custom context menu is visible; hide it
        this._hideMenu();
}
}

The _hideMenu() function that both these calls is very simple – it just hides the context menu element and sets the _menuVisible flag accordingly:

_hideMenu : function()
{    
this._menuElement.style.display = 'none';
this._menuVisible = false;
}

And thats it! The only thing left is to clean up after us, which we do by overriding the dispose method:

dispose : function()     
{
// clean up
    $removeHandler(this._contextElement, 'mousedown', this._onMouseDownHandler);  
$removeHandler(document, 'contextmenu', this._onDocumentContextMenuHandler);   
$removeHandler(document, 'click', this._onDocumentClickHandler);
Iridescence.Ajax.ContextMenuBehavior.callBaseMethod(this, 'dispose');
}

Now this is a fairly simplistic context menu extender – one might want to add asynchronous loading and maybe animation support at some point – but still, it’s quite impressive how simple the ASP.NET Ajax API makes it to write powerful, reusable components with very little code. Gotta love it :)

Download the complete source code here. (Updated 1. December 2007 – fixed a few bugs in the script).

Update 7. December 2007 –  Be sure to check out this post, which shows how to add animation support to the ContextMenuExtender.

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

8/7/2007 12:12:05 PM

mc

well, for me it worked like a charm! thanks! 😉

maybe you ought to put a small demo projec for the sake of completness.

cheers! 😉

mc

8/20/2007 12:48:07 AM

Jimmy

I got this error

Assembly ‘ContextMenu, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null’ contains a Web resource with name ‘Iridescence.Ajax.ContextMenuBehavior.js’, but does not contain an embedded resource with name ‘Iridescence.Ajax.ContextMenuBehavior.js’.

Jimmy

8/21/2007 8:18:38 AM

Fredrik

Jimmy, you need to set the Build Action on the .js file to ‘Embedded Resource’ in the project (right click and select Properties on the .js file) Smile

Fredrik

10/18/2007 12:56:58 PM

dzhang

I got the same error as Jimmy did and I did set the Build Action on the .js file to ‘Embedded Resource’ in the project, any suggestions?

dzhang

10/19/2007 9:37:36 AM

Fredrik

Hmm, the only other thing I can think of is that you’ve put the code into a different namespace? If so, you need to also change the assembly attribute that registers the embedded resource accordingly.

Fredrik

10/31/2007 10:52:45 AM

Sreekanth

I used this ContextMenuExtender inside GridView in one of my columns. I have a panel that contains two link buttons inside it in the same column of my grid.

Now, when i right click, it is properly showing the context menu, but it is always showing the panel of LAST ROW in my grid. I am not sure what is causing this beahvior.

I even tried to add code to my rowdatabound method that will properly set the ContextMenuControlID to the panel object contained in corresponding Row of the grid. But still it does not work.

If any one thinks that they can help me, please write me a line to my email address given below and i will reply with complete source code.

sreekanthgolla_2000@yahoo.com

Thank you,
Sreekanth.

Sreekanth

11/2/2007 9:49:51 AM

Sreekanth

I fixed the problem i am facing of trying to have more than one ContextMenuExtender in the same aspx page. In my case i have contextmenuextender inside gridview (in one of my columns)

Though i cannot upload the fixed source code here, the solution for the problem is quite simple:

Do not forget to prefix every member variable inside ***Behavior.js file with this. keyword.

If you need the actual fixed ContextMenuExtender.js file, drop me a line of email and i will reply to you.

-Sreekanth.

Sreekanth

11/2/2007 10:44:55 AM

Fredrik

Good catch Sreekanth!

I’ll update the post with the fixes asap Smile

Fredrik

11/9/2007 11:58:39 PM

anikin

Sreekanth, I want your fixed ContextMenuExtender.js file ,thanks

my mail address is anikin2008@hotmail.com

thanks

anikin

12/1/2007 8:14:18 PM

Michael Carr

Thanks for the code, it was exactly what I was looking for.

However, I think I found a small bug.

In your code, you reference “_contextElement” and “_menuElement”. I think you really mean to reference “this._contextElement” and “this._menuElement”. (You reference it correctly in your initialization code, but the rest of the code doesn’t)

The problem doesn’t show up until you try to use several context menus on one page and then funny things start happening.

Thanks again for a great contribution! I don’t know why Microsoft didn’t include an extender like this in the toolbox already…

Michael Carr

12/1/2007 8:25:02 PM

Michael Carr

Oops I guess the bug was already caught above. Next time I’ll read.

Michael Carr

12/2/2007 5:37:33 AM

Fredrik

Thanks Smile
I had actually fixed that bug, but apparently forgotten to update the post&source code download.. should be fixed now!

Fredrik

12/4/2007 1:46:24 PM

IT Hero

Is there a demo project?

IT Hero

12/6/2007 6:18:26 AM

Fredrik

I will be posting an update with some new features and a demo project soon Smile

Fredrik

12/7/2007 5:05:15 AM

aswood

thank you for your code

aswood

12/16/2007 4:56:25 AM

Martin

Hi there,

I have testet your extender and like it ;o)

But is it possible in anyway to add the menu to all the links in a treeview that is populated from a database and then add a ?id=1 to the links in the context menu where the the id is the id beloning to the records from the database ?

Martin

12/18/2007 9:35:43 AM

Thomas

Hi!
Wonderful work, thanks a lot.
I cannot manage this menu to be visible also when I click the left mouse button. How can this be done? I have tried to add e.button == 0 in else clause of method _onMouseDown.

Thanks,
Thomas

Thomas

12/20/2007 4:52:21 PM

Fredrik

Martin – the way the extender is implemented, this won’t be easily possible, sorry. It’s an interesting problem though, I might look into it later – but I can make no promises Smile
Thomas – Have you checked out the PopupControlExtender in the Ajax control toolkit? It can be used to show a popup on a left mouse-button click.

Fredrik

9/29/2008 1:22:04 PM

DuongNguyen

I work well but when i try using two different context menu in a page, but both of them show only the content of the second context menu, how can i fix this bug. Please help me.

DuongNguyen United States

11/10/2008 5:19:33 PM

Jacob Cordingley

Works Great I’m using it for a filter in a gridview
I was able to add a cssContextmenu to style the menu
and set focus where if the menu is a textbox it will focus to it

Jacob Cordingley United States

3/9/2009 3:20:47 PM

Ronald Langi

Hi,

This is great. I need something like this for a gridview. When I click a menu item after right clicking on a row of a gridview to bring up the context menu, how can I pass the key value of that row to the command of the context menu item in java script? I don’t want the page to postback.

Can you help me with this?

Thanks,
Ronald

Ronald Langi Republic of the Philippines

7/10/2009 3:40:08 AM

Maria

Thanks for this great post – I will be sure to check out your blog more often

Maria Republic of the Philippines

7/10/2009 5:01:57 AM

Maria

Nice blog, just bookmarked it for later reference

Maria United Kingdom

Animating an Asp.Net Ajax Control Extender

Author: Fredrik Kalseth

An entry about asp.net | ajax Publication date 7. December 2007 22:14

Earlier this year, I wrote a blog post describing how to develop a context menu control extender using the Asp.Net Ajax control toolkit. It was a fairly basic extender, allowing you to specify a context area and an associated control that should be displayed when the user right-clicked inside that area. In this post I’ll go back and enhance the extender with support for animating the context menu.

What I want to accomplish with the end result, is the ability to write markup similar to the following:

<idc:ContextMenuExtender
    ID="_cme"
    runat="server"
    ContextMenuControlID="_contextMenu"
    TargetControlID="_contextArea">
    <Animations>
        <OnShow>
            <FadeIn Duration="0.25" />
        </OnShow>
        <OnHide>
            <FadeOut Duration="0.25" />
        </OnHide>
    </Animations>
</idc:ContextMenuExtender>

If you’ve used any of the control extenders in the Ajax toolkit like the PopupControlExtender or UpdatePanelAnimationExtender, I’m sure you’ve seen that Animations tag before. It basically allows us to set up one or more storyboards for animations that should trigger on certain events – in the example above, applying a short FadeIn animation when the context menu is shown, and a short FadeOut animation when it is hidden.

The AnimationExtenderControlBase

Originally, my ContextMenuExtender inherited from the ExtenderControlBase class. The first step towards adding support for animations, is changing this to the AnimationExtenderControlBase, which will give me all the leverage I need to easily add animation support to my extender. This new base class has a few members that I’m interested in – there’s the Animations property, and the SetAnimation and GetAnimation methods. As you see from the markup above, the Animations property is the one that we’ll use to set up the storyboard for animations. The cool thing about this, is that it then automatically supports all the pre-built animation types that the toolkit contains – go take a look at the documentation to learn more about animations. The only thing we need to do to make it work, is to set up the different events that we want to support animation – in our case, they’re OnShow and OnHide. We do this by adding similarly named properties on our extender:

[ExtenderControlProperty]
[ClientPropertyName("onShowJson")]
[Browsable(false)]
public Animation OnShow
{
get
    {
return GetAnimation(ref _onShow, "OnShow");
}
set
    {
SetAnimation(ref _onShow, "OnShow", value);
}
}
private Animation _onHide;
[ExtenderControlProperty]
[ClientPropertyName("onHideJson")]
[Browsable(false)]
public Animation OnHide
{
get
    {
return GetAnimation(ref _onHide, "OnHide");
}
set
    {
SetAnimation(ref _onHide, "OnHide", value);
}
}

As you can see, these are decorated with the ExtenderControlProperty attribute to signal that I want the values they get set to, to be transported to the client-side component. Notice also that I’ve used the ClientPropertyName to change the client-side target property – I’m telling the toolkit to map the server-side property OnShow/OnHide to the client-side property onShowJson/onHideJson (or rather, the set_onShowJson/set_onHideJson and get_onShowJson/get_onHideJson methods, as JavaScript has no concept of properties).

That’s it for the server-side changes – the real stuff happens client-side, after all.

Animate Me

Our client-side stuff is defined in the ContextMenuBehavior object. The first thing we do, is to add the client-side properties that we told the server-side component to map the server-side OnShow and OnHide properties to:

get_onShowJson : function() 
{
return this._onShowJson;
},
set_onShowJson : function(value) 
{
this._onShowJson = value;
},
get_onHideJson : function() 
{
return this._onHideJson;
},
set_onHideJson : function(value) 
{
this._onHideJson = value;
}

Now, recall that the Animations property on the server-side extender control was just a string – so our _onShowJson and _onHideJson fields will just end up holding string representations of the animations – incidentally in a JSON format. We can use these strings to create AjaxControlToolkit.Animation objects, and we’ll do that in the initialize method of the component:

initialize : function() 
{
Iridescence.Ajax.ContextMenuBehavior.callBaseMethod(this, 'initialize');
// other stuff removed for brevity...
                
if(this._onShowJson)
{
this._onShowAnim = $AA.buildAnimation(this._onShowJson, this._menuElement);            
}
if(this._onHideJson)
{
this._onHideAnim = $AA.buildAnimation(this._onHideJson, this._menuElement);
}
}

Now, if the any animations were specified, we’ll have them parsed into actual Animation objects ($AA is an alias for AjaxControlToolkit.Animation) in our component, and set to target the context menu (stored in the _menuElement field), ready to be triggered whenever the context menu is shown or hidden. To trigger them, we need to modify the showMenu and hideMenu methods of the ContextMenuBehavior prototype slightly:

showMenu : function(x,y)
{    
// set flags
    this._menuVisible = true;
this._menuJustShown = true;  
this._menuElement.style.left = x + 'px';
this._menuElement.style.top = y + 'px';    
this._menuElement.style.display = '';
if(this._onHideAnim)
{
// if the hide animation is currently running, stop it
        this._onHideAnim.stop();
}
if(this._onShowAnim)
{             
this._onShowAnim.play();
}  
}

Most of this method is the same original – the only difference is that if there’s an OnShow animation specified, we start playing it, first ensuring that any OnHide animation currently playing is stopped.

hideMenu : function()    
{    
if(this._onShowAnim)
{
// if show anim is currently running, stop it
        this._onShowAnim.stop();
}
if(this._onHideAnim)
{
this._onHideAnim.play();
}     
else
    {
this._hideMenuCore();
} 
this._menuVisible = false;
}

The hideMenu method is much the same – if there’s an OnHide animation we start playing it, first ensuring that any OnShow animation currently playing is stopped.

Play With Me

That was a very quick guide to adding support for animations in an Asp.Net Ajax Control Extender. You can read more about using animations over at the Asp.Net Ajax Control Toolkit website.

If you want to play around with the ContextMenuExtender, click here to download a Visual Studio 2008 solution including the source code, and an example project which shows a few usage scenarios of the extender. Feel free to use and abuse it to your hearts content :)

Currently rated 4.0 by 1 people

  • Currently 4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

10/11/2008 8:13:24 AM

trimurthy

Iam working asp.net 2.0 I have used AnimationExtedet but it should not any onclick events or sequence tags with in animation tag.please replay that quation.

trimurthy India

ASP.NET MVC ActionResult for Rendering JSON using JSON.NET

Author: Fredrik Kalseth
An entry about asp.net mvc | ajax Publication date 1. May 2008 18:03

With the latest drop of the ASP.NET MVC framework, as I’ve mentioned earlier, controller actions now return an ActionResult object. Out of the box, you have the choice between the RenderViewResult, ActionRedirectResult, HttpRedirectResult and EmptyResult types to do different things (they’re fairly self-explanatory, no?). In the application I’m currently working on though, I have several actions which are supposed to only ever get called asynchronously from the client (using jQuery, a totally awesome JavaScript library – more on that some other time), and I want these actions to return a JSON string that can be easily consumed by the JavaScript callback handler. With the help of James Newton-Kings excellent JSON.Net library, all it took to get this working was to implement my own RenderJsonResult class:

/// <summary>
/// An action result that renders the given object using JSON to the response stream.
/// </summary>
public class RenderJsonResult : ActionResult
{
    /// <summary>
    /// The result object to render using JSON.
    /// </summary>
    public object Result { get; set; }
 
    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.ContentType = "application/json";
 
        JsonSerializer serializer = new JsonSerializer();
        serializer.Serialize(context.HttpContext.Response.Output, this.Result);
    }
}

 

My controller actions can then use the anonymous object notation of C# 3.0 to render JSON output:

return new RenderJsonResult { Result = new {status = "ok", assignedId = newItem.Id} };

 

Awesomeness! :)

Currently rated 4.3 by 7 people

  • Currently 4.285714/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

5/1/2008 4:47:52 PM

Kenneth Solberg

Wow, that was really smooth! Will replace my preview 1 View rendering JSON with this way of doing it. Oneliners ftw!

Kenneth Solberg

9/25/2008 5:37:34 AM

Dave

Have you done anything where you are posting back complex types to your controllers?

i.e. suppose you want to post to /Employee/Create and the Create method takes an Employee object…

Thoughts?

Dave

Dave United States

9/25/2008 5:08:43 PM

Fredrik

@Dave, I don’t think it makes much sense to have action methods that take complex objects. I would probably instead have a method like EmployeeController.Create(string name, string address, … Check out my other article on ASP.NET MVC + jQuery and you’ll se an example of this. iridescence.no/…/…h-ASPNET-MVC-and-jQuery.aspx

Fredrik Norway

12/8/2008 5:19:32 AM

Rean

Hi Fred,
In asp.net webforms I used James Newton-King’s Jayrock json serializer to send json objects to server side as .net objects. For e.g. I would send a json object to a JsonRpcHandler method with attribute JsonRpcMethod and it would accept it as an IDictionary. I will than play with it and send back a .net serializable object which would automatically be converted to json by the handler. This way the two way communication is json.
How will I achieve this in asp.net mvc?
Confession: I haven’t explored asp.net mvc a lot.

Rean India

3/16/2009 12:01:51 PM

virus

when i use you code,for example

public class ShiwbController : Controller
{

public ActionResult ShowJson()
{
var json = new User { Name = “author”, Sex = “male” };
return new RenderJsonResult { Result = new { status = “ok”, assignedId =123 } };

}
public ActionResult js()
{
return JavaScript(“var i=0;”);
}
}
public class RenderJsonResult : ActionResult
{
public object Result { set; get; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ContentType = “applicaion/json”;
Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Serialize(context.HttpContext.Response.Output, this.Result);
}
}

when i visit http://localhost/showjson ,there is a messagebox to let me download file “showjson”,and this is appear when i visit http://localhost/js , why not?
thank you

virus People's Republic of China

Invoking ASP.NET MVC Actions from JavaScript using jQuery

Author: Fredrik Kalseth

An entry about asp.net mvc | ajax | javascript Publication date 31. May 2008 11:27

One of the things that the MVC model is really great at, is integrating with Ajax. I blogged about a RenderJsonResult class a few weeks ago that one could use to create controller actions which render their output as Json – since then the last ASP.NET MVC framework drop also includes a JsonResult type of its own. What I didn’t talk about in the mentioned post, was how to actually invoke such actions from JavaScript; enter jQuery.

Ajax with JQuery

In the crowd of JavaScript libraries out there, JQuery is probably the most unique – at least for now. Its main features are the abilities to query and manipulate the DOM using syntax that anyone familiar with CSS will feel at home with. But jQuery offers more than this – it also has an Ajax API. With this, we can easily perform a POST or GET on a controller action and handle the result it returns asynchronously.

As an example, lets assume we have a FeedbackController with an action Submit:

public ActionResult Submit(string author, string email, string comment)
{
    // logic for submitting feedback omitted
 
    return new RenderJsonResult {Result = new {success = true, message = "Thank you! We value your feedback."}};
}

 

Invoking this from JavaScript using jQuery is super easy:

$.ajax(
{
   type: "POST",
   url: "/Feedback/Submit",
   data:"author=" + author + "&email=" + authorEmail + "&comment=" + comment,
   success: function(result)
    {
        if(result.success) $("#feedback input").attr("value", ""); // clear all the input fields on success
        $("#feedback_status").slideDown(250).text(result.message); // show status message with animation
    },                
   error : function(req, status, error)
   {
        alert("Sorry! We could not receive your feedback at this time.");   
   }
});

 

We set the type of the call to POST, because we need to send some data with our request, which we use the data option to specify. jQuery allows us to provide a few callback methods that will be invoked on the success or failure of the Ajax call. If our call is successful, the success callback gets invoked, which gets passed an object representing the result of the Ajax call. jQuery is able to handle results formatted in different styles, including xml, html, script and json. You can specify the expected data type using the dataType option. Leaving it out will cause jQuery to choose the type based on the MIME type of the response, which is usually fine. There are other options which can be used; you’ll find a complete description of them here. The code in the success callback uses the selectors, attributes, manipulation and effects APIs to reset the input fields and tell the user that the feedback was received.

It’s simple, it’s elegant – and so, so far removed from the bloated UpdatePanels of ASP.NET.

Surface Scratched

This post merely scratches the surface of what is possible when combining ASP.NET MVC with jQuery (or other Ajax APIs for that matter). Look out for more posts on this topic in the future!

Currently rated 4.2 by 20 people

  • Currently 4.2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

8/5/2008 4:21:16 AM

Michael Hart

Simpler:

return Json(new {success = true, message = “Thank you! We value your feedback.”});

Michael Hart Australia

8/5/2008 10:45:22 AM

Fredrik

@Michael: Yeah, you’re right – but this post was written using the preview 2 of the ASP.NET MVC framework; they didn’t add the Json() methods until later Smile

Also note that the Json() methods in preview 4 uses the JavaScriptSerializer class internally; my approach uses the JSON.NET framework.

Fredrik Norway

12/19/2008 11:23:35 AM

Alexis

Great post – much less “hack-ish” than a lot of the other tutorials out there.

Alexis South Africa

1/27/2009 2:45:24 AM

pingback

Pingback from goneale.wordpress.com

Submitting an AJAX Form with ASP.NET MVC + jQuery « {Programming} & Life

goneale.wordpress.com

4/1/2009 2:47:42 PM

devix

Nice Information……….

devix United States

4/3/2009 10:48:36 PM

Jason

Exactly what I needed. Very helpful.

Jason United States

6/22/2009 3:37:46 AM

Praveen

I believe you need to add the below definitions while doing a jQuery .ajax

contentType: “application/json; charset=utf-8”,
dataType: “json”

I needed the above to make it work, esp. processing the returned result at the
Javascript end.

-Praveen

Praveen Australia

7/10/2009 2:43:46 AM

Paul

Nice blog, just bookmarked it for later reference

Paul Republic of the Philippines

7/10/2009 4:06:13 AM

Paul

BAAAM Nice Post dude! Do more >D

Paul United Kingdom

1 2 3 18