MVC3 Razor – jQuery – Visual Studio != Intellisense

I wondered where my intellisense had gone for jQuery with MVC3 and Razor. Anyway there is a fix for it:

Add the following to your view (with the jQuery vsdoc version you have:

@if (false) { <script src="~/Scripts/jquery-1.5.0-vsdoc.js" type="text/javascript"></script> }

The if-statement prevents the script tag from being rendered into the html source code.

Grab jQuery 1.5.0 vsdoc from here -> http://damianedwards.com/files/jquery/jquery-1.5-vsdoc.js

Cannot have multiple items selected in a DropDownList (ASP.Net)

Nasty problem. Lesson learnt.

I could not figure out why I was seeing this error, clearselection, setting index -1 etc, nothing worked when trying to set a dropdownlist selected value from code behind.

Turns out it was because I was adding a ListItem to multiple dropdownlists without instantiating a new one for each dropdownlist. This caused all the problems I was seeing.

For every Dropdownlist, create a new instance of the ListItem object before adding it – do not share it accross controls.

Firefox refresh page retaining checkbox/radiobutton values

I had a page which uses codebehind Page_Load and (!IsPostBack) to setup all the controls on the page depending on what was being loaded. This worked fine, apart from when I refreshed the page (F5) in Firefox 3.5 – IE was okay.

Firefox seems to retain all the input selections – eventhough from the code behind I was ressetting them.

The only way I found to resolve this was to call a reset on the form (actually in my Master page) in the document ready function of JQuery which solves the problem.

$(document).ready(function() {

$(“#<%= (form1.ClientID) %>”)[0].reset();

});

Problem with ASP.Net & Radiobuttons in repeaters/datalists/datagrids all being selectable

RadioButtons place on a page inside a repeating control (repeater/datalist/datagrid), you set the group but they are still all individually selectable.

I have come across this problem before, which was fixed using some client side script added to the radiobuttons, but this had to be done for each radiobutton group as I added them and was a bit of a pain.

I have recently found a much better solution here -> http://www.codeproject.com/KB/webforms/How_group_RButtons.aspx

Works perfectly well. Unstructions:

1) Just download the zip file at the top of the page.

2) Unzip and place the file (GroupRadioButton.dll) into your bin folder.

3) Add a reference to the assembly into your web.config or .aspx page as below:

<%@ Register TagPrefix=”vs” Namespace=”Vladsm.Web.UI.WebControls” Assembly=”GroupRadioButton” %>

Use the control on your page as you would a RadioButton

<vs:GroupRadioButton id=”MyRbn” runat=”server” GroupName=”MyRbnGrp” />

Thats it. Brilliant 🙂

Kudos to Vladimir Smirnov.

ASP.Net UpdatePanel breaks Javascript/JQuery e.g. Slimbox, Tooltip…

After using ASP.Net Ajax components such as an updatepanel on your page you may see that some of your Javascript/JQuery functions do not seem to work once a partial page update has been done. This is because thanks to the partial page update those items contained within it have been reloaded but no functions have been rebound to them.

I have used 2 solutions for this, one is JQuery Live Query. You can use this to simply rebind to any item reloaded for example I used this to rebind the elements I had previously set for Slimbox and set the rel=lightbox attribute for them:

$(“a[rel^=’lightbox’]”).livequery(function() {
$(this).slimbox();
});

This finds any anchor element with the rel=”lightbox” tag and binds the slimbox function.

Alternativly to this you can replace the

‘$(document).ready(function() {

// do stuff

});

with

function pageLoad(sender, args)
{
// do stuff

if (args.get_isPartialLoad())
{
//Specific code for partial postbacks can go in here.
}
}

But be aware this can only be used once on the document, if you need to do this in multiple places use:

Sys.Application.add_load(function() {

// do stuff

});

Multiple arguments with CommandArgument

Handy tip for passing as many arguments as you like with an OnCommand event.

Simply add the attributes you want to pass and the values:

<asp:LinkButton  ID=”LinkButton1″ runat=”server” OnCommand=”link_Clicked” CommandArgument='<%# Eval(“arg1”) %>’ NewArg='<%# Eval(“arg2”) %>‘>Link Here</asp:LinkButton>

Then in the event handler you can access them from the sender attributes:

protected void SubCatLink_Clicked(object sender, CommandEventArgs e)
{
LinkButton link = (LinkButton)sender;
String NewVal = link.Attributes[“NewArg”].toString();
}

Simple.

Rescale and save Image on the server using ASP.Net GetThumbnailImage

A quick function I use to save a rescaled version of an image during upload.

Handle the upload click and do the rescaling:

protected void UploadFileClick(object sender, EventArgs e)
{
    // get the upload control
    FileUpload FileUpload1 = (FileUpload)ColourFV.FindControl("FileUpload1");
    // get the filename
    String strFileName1 = FileUpload1.PostedFile.FileName;

    if (strFileName1 != "")
    {
        //Grab the file name from its fully qualified path at client 
        TextBox FilenameProfileTbx1 = (TextBox)ColourFV.FindControl("FilenameProfileTbx1");
        //only the attached file name not its path
        String fileName2 = System.IO.Path.GetFileName(strFileName1);

        //Save uploaded file to server 
        try
        {
            FileUpload1.PostedFile.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["your setting"]) + fileName1);
        }
        catch (Exception ex)
        {
            // do any error handling u like here
        }

        // Now this function is called to rescale and save 
        RescaleAndSaveImge((Server.MapPath(ConfigurationManager.AppSettings["your setting"]) + fileName1),
            (Server.MapPath(ConfigurationManager.AppSettings["your setting"]) + "Thumbnails/" + fileName1), 155, 81);

    }

Here is the code for the function to rescale:

    public bool ThumbnailCallback()
    {
        // do any error handling here
        return false;
    }
    
    // TargetImgFile = filepath of image saved to the server which you want to rescale
    // DestImgFile = filepath of the new image you want to save to
    // NewWidth = new width in px 
    // NewHeight = new height in px
    public void RescaleAndSaveImge(String TargetImgFile, String DestImgFile, Int32 NewWidth, Int32 NewHeight)
    {
        System.Drawing.Image.GetThumbnailImageAbort myCallback = 
            new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); 

        using(System.Drawing.Image TargetImage =
            System.Drawing.Image.FromFile(TargetImgFile))
        { 
            using (System.Drawing.Image Thumbnail = 
                TargetImage.GetThumbnailImage(NewWidth, NewHeight, myCallback, IntPtr.Zero)) 
            {
                Thumbnail.Save(DestImgFile); 
                Thumbnail.Dispose(); 
            } 
            TargetImage.Dispose(); 
        } 

    }

Checkbox OnCheckChanged within datalist/repeater/gridview controls do not fire ItemCommand event

I needed a checkbox inside a datalist to call a function when selected/unselected and found it would not fire. It did not raise the container controls itemcommand event.

Here’s a workaround that worked:

Next to your checkbox, create an asp:button with style=”display:none” so that it’s hidden, but enabled. I created a call with this one attribute and set the CssClass=”hider”.

In the codebehind, automate a click of the button when the checkbox (chk) is clicked by doing:

    chk.Add("onclick", "javascript:document.getElementById('" + btn.ClientID + "').click()");

When you check/uncheck the checkbox, the button’s click event will fire and also raise the ItemCommand event on its parent container and you can then do what you need to do here.