jQuery Modal Dialog Helper in ASP.NET Web Pages

10. November 2011 19:26

Now that I have been working on a few new projects (which I'm very exited to get launched), I've decided to write them using ASP.NET Web Pages. I am using Visual Studio instead of WebMatrix.  I steered away from Web Forms this time around to try something new and see how it goes. So far so good. I am loving ASP.NET Web Pages and find it very fast and powerful and easy to integrate javascript with data I would normally have trouble with in Web Forms. I will admit, I do miss the whole "code-behind" concept from Web Forms. However, either MVC or architecting out the ASP.NET Web Pages app can make up for it pretty easily.

Anyway, Helpers in Web Pages I have found to be very effective. If any of you use jQuery or jQuery UI, then you understand how awesome they both are.  I created simple Helpers to show a jQuery UI Modal Dialog and I hope you find them useful. They are easy to implement on your web page and easy to implement as a Helper. 

This assumes you have a reference to the propery jQuery scripts either on a layout page or the page you will be using these helpers.  I have made two of them. One for a success message and one for an error message.  You'll notice image reference. They are basically a chosen success icon and error icon, so replace as needed.

Code for the helpers

@helper GetSuccessMessage(string dialogID, string autoOpen, string title, string message)
    {
    <script type="text/javascript">
        $(function () {

            $("#@dialogID").dialog({
                autoOpen: @autoOpen,
                height: 200,
                width: 500,
                modal: true,
                title: '@title',
            });
        });
    </script>
    
    <div id="@dialogID" style="padding: 10px 10px 10px 10px">
        <table cellpadding="5" cellspacing="5" style="width: 100%; border: 1px solid green;">
            <tr>
                <td valign="top">
                    <img src="@Href("~/images/success.png")" alt="success" />    
                </td>
                <td valign="top">
                    @message
                </td>
            </tr>
        </table>
    </div>
    
}

@helper GetErrorMessage(string dialogID, string autoOpen, string title, string message)
{
    <script type="text/javascript">
        $(function () {

            $("#@dialogID").dialog({
                autoOpen: @autoOpen,
                height: 200,
                width: 500,
                modal: true,
                title: '@title',
            });
        });
    </script>
    
    <div id="@dialogID" style="padding: 10px 10px 10px 10px">
        <table cellpadding="5" cellspacing="5" style="width: 100%; border: 1px solid red;">
            <tr>
                <td valign="top">
                    <img src="@Href("~/images/error.png")" alt="error" />    
                </td>
                <td valign="top">
                    @message
                    <br /><br />
                    If problem the persists please email <a href="mailto:something@something.com">support@something.com</a> with a description of your issue.
                </td>
            </tr>
        </table>
    </div>    
}

Now this is how you would use them in your Web Page.

@SiteHelpers.GetSuccessMessage("dialog-success", @isValid.ToString().ToLower(), "", @confirmationMessage)

@SiteHelpers.GetErrorMessage("dialog-error", @isError.ToString().ToLower(), "", @confirmationMessage)

 

//TODO: rest of code above to perform any action
if(yourVariable)
{
    isValid = true;
    isError = false;
    confirmationMessage = "Item has been updated.";

}                    
else
{
    isValid = false;
    isError = true;
    confirmationMessage = "Error updating item. Please try again";
}

Well I hope you find these jQuery UI Modal Dialogs easy to use in your ASP.NET Web Pages application.  Now that's I've done two full apps, I found myself using them all the time.

References

http://jquery.com/

http://jqueryui.com/demos/dialog/

http://www.asp.net/webmatrix/tutorials/3-creating-a-consistent-look 

 

Tags:

ASP.NET Web Pages | Javascript

Using Plupload in ASP.NET

7. July 2011 18:21

Test Solution Download

PLUploadTest.rar (121.28 kb)

I like plupload, however, using it for a real world application was a bit tough my first time around.  I basically wanted to have the user upload a file, then record that record in the database.

So I made a skeleton version of the code that you can use to help get you started. This will allow you to use Plupload in your asp.net application to do the following:

  • have the user select a file (or files) via plupload
  • Have the user submit a file(s)
  • Have a generic handler be aware of the id's of a given object(s) (i.e., a user id)
  • Store the file uploaded into a given directory
  • The ability to store the id's of an object(s), file id and file name from plupload

To accomplish this you will need the following:

  • Plupload
  • Custom javascript (not too much) you will see a file named xdev.plupload.js in js/plupload
  • Enable Page Methods via the ASP.NET ScripManager

 

Once you have a skeleton version of the code you like, I think you'll find it easy to modify and incorporate plupload into your project as well. I love this multifile upload, so why not use it effectively in your website application :)

I will bascially do a copy and paste of the ASP.NET code so you can see what's going on.  I think the best thing about this is the ability to take the files and the ID of your object (i.e., user id) that is uploading them and storing the data in a database.

PLUploadTest.aspx

In the "head" part of the aspx page you will need to reference the following javascript and css

    <script type="text/javascript" src="https://www.google.com/jsapi">
    <script type="text/javascript">
        google.load("jquery", "1.3");
    </script>
    <script src="js/plupload/plupload.full.min.js" type="text/javascript">
    <script src="js/plupload/jquery.plupload.queue.min.js" type="text/javascript">
    <script src="js/plupload/xdev.plupload.js" type="text/javascript">
    <link href="plupload.queue.css" rel="stylesheet" type="text/css" />

In the body section of the ASPX page you will need the following:

    <form id="form1" enctype="application/x-www-form-urlencoded" method="get">

        <div id="uploader" style="width: 525px;">
            <p>You browser doesn't have Flash, Silverlight, Gears, BrowserPlus or HTML5 support.

</div> <br /> <div style="width: 150px; margin-right: 490px;"> <a onclick="SubmitItem(this)" href="#">Submit Item </div> </form>

PLUploadTest.aspx.cs

[WebMethod]
public static string GetIDs()
{
    //This is strictly here just so you can see how you can grab ID's and make plupload aware of them
    //This is useful for data driven application. Example, you need the ID of the user who is uploading a file
    //so you can pull that data out later when the user logs in.

    //default is pipe delimited for js file in function OnGetIDSucceeded
    //IDOfObject1|IDOfObject2
    string IDs = "0|0";

    //These IDs could be pulled from anywhere (i.e, Session, DB, XML file)

    IDs = string.Format("{0}|{1}", "10", "11"); //"10" and "11" and filler so you can have data to mess around with

    return IDs;
}


[WebMethod]
public static void InsertFileRecord(string idOfObject1, string idOfObject2, string fileID, string fileName)
{
    _InsertAttachment(idOfObject1, idOfObject2, fileID, fileName);
}



private static void _InsertAttachment(string idOfObject1, string idOfObject2, string fileID, string fileName)
{
    //TODO: Insert into Database as needed, or whatever data store you are using.
    string doSomething = ""; //left here for debugging purposes...delete as needed
}

UploadHandler.ashx.cs

 

public void ProcessRequest(HttpContext context)
{
    //TODO: Whatever you would like to do now that you have the ID's of the objects
    //Example, could be creating directories for that ID specifically, etc....        
    string _idOfObject1 = context.Request.Headers["IDofObject1"].ToString();
    string _idOfObject2 = context.Request.Headers["IDofObject2"].ToString();

    int chunk = context.Request["chunk"] != null ? int.Parse(context.Request["chunk"]) : 0;
    string fileName = context.Request["name"] != null ? context.Request["name"] : string.Empty;

    //TODO: change as needed for your application
    string uploadPath = context.Server.MapPath("~/documents/"); 

    HttpPostedFile fileUpload = context.Request.Files[0];

    fileName = fileName.Insert(0, string.Format("{0:MM}{0:dd}{0:yyyy}", DateTime.Now));

    using (var fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
    {
        var buffer = new byte[fileUpload.InputStream.Length];
        fileUpload.InputStream.Read(buffer, 0, buffer.Length);

        fs.Write(buffer, 0, buffer.Length);
    }

}

public bool IsReusable
{
    get { return false; }
}

 

 

One of the custom javascript methods that handles the files and data. Please download the zip file to see the entire solution.

 

function SubmitItem(e) {

    //get a copy of the current uploader
    var uploader = $('#uploader').pluploadQueue();
    var obj = uploader.settings;

    //alert("Local js variable ID1: " + IDofObject);
    //alert("Local js variable ID2: " + IDOfObject2);

    //alert("Header Object1: " + obj.headers.IDofObject1);
    //alert("Header Object2: " + obj.headers.IDofObject2);

    // Validate number of uploaded files
    if (uploader.total.uploaded == 0) {
        // Files in queue upload them first
        if (uploader.files.length > 0) {
            // When all files are uploaded submit form
            uploader.bind('UploadProgress', function () {
                if (uploader.total.uploaded == uploader.files.length)
                    $('form1').submit();
            });

            //now go insert the files into the DB
            uploader.bind('UploadComplete', function (up, f) {

                var obj = up.settings;

                //alert("Upload Complete");

                for (i = 0; i < f.length; i++) {

                    //alert("Name: " + f[i].name);
                    //alert("ID: " + f[i].id);

                    InsertFileRecord(obj.headers.IDofObject1, obj.headers.IDofObject2, f[i].id, f[i].name);
                }

                alert("File(s) Uploaded"); //You may not want this. I just left it here so you can see how it interacts with everything else.

            });

            uploader.start();
        }
        else {

            alert("No files to upload"); //take out or do whatever you would like here because there were zero files
        }
    }

}

 

Resources

http://www.plupload.com/
http://www.plupload.com/example_queuewidget.php
http://www.plupload.com/example_custom.php
http://www.plupload.com/example_events.php
http://www.plupload.com/plupload/docs/api/index.html

 

 

PLUploadTest.rar (121.28 kb)

Tags:

ASP.NET | Javascript

jQuery Image Rotator for ASP.NET - Part II

9. February 2010 17:43

Before I wrote a post about how to create a simple jquery image rotator in asp.net. I'v expanded on that code to include the ability to "browse images" in the slideshow by clicking on a number for the image. The end result now looks something like this. Please ignore the size and width (these can be set) and this is just for pure example. Also please ignore the bad looks of the play button as well. Again, just for example. I will also include a zip file as well.

 

 

Since I'm expanding on my first post, I will just be adding the code I changed to to make this happen. 

Let's start with the code behind file.  Our goal here it to create the numbers that users can use to navigate the slideshow we created.  Also, we are adding a simple title text saying "Browse Image".  We will be doing this by taking a count of how many images we have and writing out a div container with nested div's.  Please see the code snippet below. 

 

That is it for the changes to our code behind file. The rest is for javascript and CSS.

The CSS aspect is pretty self explanitory.  As you can see from the code snippet above we gave our div's ID's. This is how we will use CSS with them.  Below are the CSS classes I added to this solution.

 

 

Ok, now for the javascript code.  Which, by the way, if any of you have suggestions on how to make this more simple or more efficient please let me now. As I was coding this it just seemed as though I could have done it a better way, but this worked so I'm sticking with it :)  I changed enough code here that I will paste the javascript as is on my control.  I have comments below in the code to help make some sense of it.

That is about it.  Again, please read my first post about this so it makes more sense.  The first post also shows you how to apply the user control to a page and set it's properties that it needs.  Below is the zip file as well.

 

ImageRotator.zip (3.13 kb)

 

 

Tags:

ASP.NET | Javascript

Call WebMethod from Javascript in ASP.NET

6. November 2009 17:24

I needed to be able to remove a session variable from javascript so this post will talk about how to call a webmethod from javascript to remove a session item.  I will be utilizing a JS file, ASP.NET page with a WebMethod exposed in it and an asp.net user control.

The basis of this is a few things:

First we need an <asp:ScriptManager> on the ASPX page with the EnablePageMethods property set to true:

Second we need to expose a static function in our ASPX code behind so it can be available to our javascript file.

Note the [WebMethod] above the function and that the function is static. This is what allows us to make it available to the javascript file.  

Please make sure to add the statement using System.Web.Services; into the ASPX page, otherwise [WebMethod] will throw an error when compiling.

Third we need a ScriptProxyManager on the ASCX control with a reference to your JS file. This will also take care of including the JS file for your control as well so there is no need to add the <script src=....> tag. Put this as the first thing in your ASCX control.

Fourth we need the code from the JS file to bring it all together:

--------------------------------------------------------------

Anywhere in your javascript you can call the ClearSessionItem() method. Such as

function MyFunction(item){
    
    ClearSessionItem("MySessionItem");
}

Also you could call it via an onclick event with an HTML element such as:

<span onclick="ClearSessionItem('MySessionItem')">Clear Item</span>

---------------------------------------------------------------
Of course you can use this concept for almost about anything.  It allows you to not have a seperate ASMX file (Web Service) in your project.  Again, the concept here allows you to call a server side method inside javascript.


Resources:

http://www.asp.net/ajax/documentation/live/Tutorials/ExposingWebServicesToAJAXTutorial.aspx
http://www.asp.net/ajax/documentation/live/ViewSample.aspx?sref=Sys.Net.PageMethod%23PageMethod.aspx
http://www.asp.net/AJAX/Documentation/Live/ViewSample.aspx?sref=Sys.Net.PageMethod/cs/PageMethod.js


Good luck...leave questions if you got them and I'll do my best to answer  

Tags: ,

ASP.NET | Javascript

jQuery Modal Dialog inside ListView ASP.NET 3.5

3. November 2009 07:12

While working on a current project I wanted to use jquery to show a modal dialog for product information.  However, I wanted to do this within a ListView and without having to having multiple dialogs rendered out to the page.  With this solution you have one ListView and one modal dialog. Within the ListView you setup parameters to pass into the javascript function.  I will give snippets of code to keep it clean.

Environment:

  • ASP.NET 3.5 SP1
  • VS 2008 SP1
  • jQuery 1.3.2
  • jQuery 1.7.2 UI (js file, css and images)

Assumptions: You are somewhat familiar with jQuery and know how to call a dialog using jQuery.  If you are unfamiliar with this please look at this page.

Before I go on with the rest, I went ahead and downloaded a custom jQuery UI package here:

http://jqueryui.com/download

I unpackaged the theme and integrated it into my website.  This was basically copying the CSS, JS and image files from the package created from jQuery.

I will not get into how to integrate it into your website because the directory structure could be different.  Make sure that your CSS matches up with where your images are though.

Ok so here is the code snippets to accomplish having a ListView and showing a jQuery modal dialog box.

NOTE: Please make sure to add the reference to your stylesheets and javascript files within your page this will be on.

Set the DIV for the modal dialog to none

Javascript function that populates the fields within the DIV for the modal dialog


ItemTemplate within your ListView (this is mine)


DIV used for jquery modal dialog

 

This may seem a bit too much at first, but once applied to your code it's not much at all.  You may need to tweek this a bit to fit your solution as this is a solution for a project I was working on.  However, it shouldn't take much tweeking once you have it in place.  The concepts above will provide you with a solution. A review of the concepts again:

  • implementing jQuery and jQuery UI
  • Have a DIV on the page to act as the modal dialog
  • Set the style of the DIV to display none
  • Within your ListView use string.format to write out a span tag that with an onclick event will pass in parameters to a javascript function
  • The javascript function will take care of calling the jQuery dialog and populate the HTML elements within your DIV. 

Questions leave a comment or send an email.  Good luck

Tags:

ASP.NET | Javascript




My Random Thought

I think the OCW is a great thing to have available to those who are in school, just finished school or just want to educate themself

http://ocwconsortium.org/

John On Twitter

Discounts