Dustin Horne - jQueryDeveloping for fun...https://www.dustinhorne.com/
http://www.rssboard.org/rss-specificationBlogEngine.NET 3.2.1.5en-UShttps://www.dustinhorne.com/opml.axdhttp://www.dotnetblogengine.net/syndication.axdDustin HorneDustin Horne0.0000000.000000Consuming RSS Cross-Domain in jQuery and MVC<p>AJAX is a powerful tool for making asynchronous requests from the client.&nbsp; Unfortunately, this is often limited to same domain requests due to security restrictions put in place to prevent cross site scripting.&nbsp; This also makes it difficult to consume external data such as RSS feeds if&nbsp;a security policy hasn't been put in place to allow cross domain callers with javascript.&nbsp; In these cases it's necessary to use your server to proxy the data back to your page. </p>
<p>Fortunately this is very simple.&nbsp; For brevity, I'm going to pass the feed URL as a parameter directly to my controller and return the feed.&nbsp; In practice, you should verify the source of the request and accept some sort of identifier, storing your feed urls server side to prevent others from exploiting your site.&nbsp; I'm going to use a random feed from Feedburner.</p>
<h2>Creating the Proxy</h2>
<p>We're going to start&nbsp;by creating an extremely simple controller action.&nbsp;&nbsp;This actually simply downloads the contents of the feed and returns the raw text back to your script.&nbsp; You can&nbsp;put this action into any controller you wish.&nbsp; I'm going to put it in my Home controller so the path to access the action will be "/home/getfeed" and it will take a parameter called feedUrl which will be a URL Encoded value.&nbsp; Since we're passing the url as an encoded querystring parameter, we have to disable input vaidation.&nbsp; Here is the controller action:</p>
<pre class="brush: c-sharp;">[ValidateInput(false)]
[HttpGet]
public string GetFeed(string feedUrl)
{
using (var c = new System.Net.WebClient())
{
return c.DownloadString(Server.UrlDecode(feedUrl));
}
}</pre>
<p>Looking at the code above you can see that the GetFeed action method simply downloads the contents of the target URL and returns it to the client.&nbsp; Now let's look at the javascript.&nbsp; I'm using jQuery and jFeed to process the RSS and display in on the page.&nbsp; If you don't have jFeed you can <a title="jFeed on GitHub" href="https://github.com/jfhovinne/jFeed/tree/master/build/dist" target="_blank">download it here</a>.&nbsp; To start with, download jquery.jfeed.pack.js and save it into your scripts folder.&nbsp; If you already have a jQuery reference, you can just add a link to the jFeed script to your &lt;head&gt; section, otherwise add both of the following:</p>
<pre class="brush: xml;">&lt;script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="/scripts/jquery.jfeed.pack.js"&gt;&lt;/script&gt;</pre>
<p>Next, add a container to your page to hold the RSS Content:</p>
<pre class="brush: xml;">&lt;div id="feedItems"&gt;&lt;/div&gt;</pre>
<p>And finally, just before your closing body tag, add the javascript to access your feed data.&nbsp; For this example, we're going to output a link to the article:</p>
<pre class="brush: js;">&lt;script type="text/javascript"&gt;
$().ready(function () {
//Use feedItems to see if an error was thrown.
$('#feedItems').ajaxError(function (event, request, settings, thrownError) {
$(this).text('There was a problem downloading the feed. ' + thrownError);
});
//Get the feed and output the links
var feedUrl = "http://feeds2.feedburner.com/PolymorphicPodcast";
var getUrl = '/home/getfeed/?feedUrl=' + encodeURIComponent(feedUrl);
var container = $('#feedItems');
$.getFeed({
url: getUrl,
success: function (feed) {
$(feed.items).each(function () {
$('&lt;p/&gt;')
.append($('&lt;a/&gt;')
.attr('href', this.link)
.text(this.title))
.appendTo(container);
});
}
});
});
&lt;/script&gt;</pre>https://www.dustinhorne.com/post/2012/03/21/Consuming-RSS-Cross-Domain-in-jQuery-and-MVC
nebraskadev@gmail.comhttps://www.dustinhorne.com/post/2012/03/21/Consuming-RSS-Cross-Domain-in-jQuery-and-MVC#commenthttps://www.dustinhorne.com/post.aspx?id=b0062e2f-3082-422d-8fd9-936c4456ea8aWed, 21 Mar 2012 18:27:00 -0700jQueryASP .NET MVCDustinhttps://www.dustinhorne.com/pingback.axdhttps://www.dustinhorne.com/post.aspx?id=b0062e2f-3082-422d-8fd9-936c4456ea8a0https://www.dustinhorne.com/trackback.axd?id=b0062e2f-3082-422d-8fd9-936c4456ea8ahttps://www.dustinhorne.com/post/2012/03/21/Consuming-RSS-Cross-Domain-in-jQuery-and-MVC#commenthttps://www.dustinhorne.com/syndication.axd?post=b0062e2f-3082-422d-8fd9-936c4456ea8aMetro Style UI With jQuery<p>Lately I've been toying around with the idea of incorporating Metro style elements into web designs.&nbsp; It seems to be a trendy thing to do lately and a lot of sites have been doing it so I started experimenting with using jQuery to achieve some of the effects.&nbsp; There are already several Metro plugins for jQuery and jQuery UI but I wanted to write my own code and see what kind of effects I could achieve.&nbsp; I've setup a demo site that I'm using my my Metro UI playground.&nbsp;</p>
<p>If you want to see what I've setup you can view the source however I'll caution you that I'm just hacking it together for now and it's nowhere near production ready.&nbsp; The purpose of the site and code for now is to just incorporate the visual and functional elements.&nbsp; Once I'm happy with the results, I'll be rewriting and refactoring all of the javascript to&nbsp;make it suitable for use and especially easier to theme with CSS (currently alot of the CSS is being implemented stricly with javascript so I can tweak it easily).</p>
<p>I&nbsp;have several demos setup already.&nbsp; The live tiles use setInterval and run on a constant loop currently but I will be modifying them to use a setTimeout and make them "pausable" and allow the animations to be changed and removed as well, and hopefully a more solid base of animations.&nbsp; I'll also be working on compatibility with touch screen devices.&nbsp; Here is a list of the currently available demos:</p>
<p><span style="font-size: small;"><strong><a href="http://metro.dustinhorne.com/" target="_blank">Live Tiles</a><br /><a href="http://metro.dustinhorne.com/demo/list" target="_blank">List</a><br /></strong></span><span style="font-size: small;"><strong><a href="http://metro.dustinhorne.com/demo/scrollbox" target="_blank">Scrollbox</a><br /><a href="http://metro.dustinhorne.com/demo/pivot" target="_blank">Pivot</a></strong></span></p>https://www.dustinhorne.com/post/2012/02/21/Metro-Style-UI-With-jQuery
nebraskadev@gmail.comhttps://www.dustinhorne.com/post/2012/02/21/Metro-Style-UI-With-jQuery#commenthttps://www.dustinhorne.com/post.aspx?id=06420868-5e11-4d48-aa54-39bbfdc58b17Tue, 21 Feb 2012 07:07:00 -0700jQueryDustinhttps://www.dustinhorne.com/pingback.axdhttps://www.dustinhorne.com/post.aspx?id=06420868-5e11-4d48-aa54-39bbfdc58b172https://www.dustinhorne.com/trackback.axd?id=06420868-5e11-4d48-aa54-39bbfdc58b17https://www.dustinhorne.com/post/2012/02/21/Metro-Style-UI-With-jQuery#commenthttps://www.dustinhorne.com/syndication.axd?post=06420868-5e11-4d48-aa54-39bbfdc58b17AJAX File Uploads with jQuery and MVC 3<p>Recently I was working on a project that required upload of images.&nbsp; I wanted to upload the images AJAX style without refreshing the page and thought jQuery would be a good fit.&nbsp; Using jQuery to post standard forms is extremely simple, but when posting multi-part forms for uploading files it's not so intuitive.&nbsp; This is due to browser security restrictions and sandboxing.&nbsp; Today I'm going to show you how to fake an asynchronous upload without reloading the page and get a result back from the server. </p>
<h2>How It Works</h2>
<p>In order to make the&nbsp;AJAX style file uploads work, we need to to post to an iFrame.&nbsp; We're going to position an iFrame off the page to hide it and then post to it.&nbsp; We'll return a result to the page&nbsp;and retrieve it with our javascript.&nbsp; It's important to note that due to security limitations, the page being posted to must be on the same domain as the page you're posting from.&nbsp; Also, I won't be demonstrating any progress indicators but in production I would highly recommend you disable the upload from and use a progress indicator to&nbsp;let your users know the file is uploading.&nbsp; Also, this solution will be using a single hidden iFrame, but for multiple simultaneous uploads you could dynamically generate the iFrames and post to them.</p>
<h2>A Couple of Problems</h2>
<p>Before we get into details I want to point out a couple of issues that&nbsp;I ran into.&nbsp; First of all,&nbsp;if you're returning a standard JsonResult from your MVC Controller, the browser will prompt you to download the file.&nbsp; To avoid this issue, we're going to inherit from the base JsonResult class and create our own that will wrap the JsonResult in a named textarea element and set the return content type to text/html.</p>
<p>The second issue is in attaching the onload event to the iFrame.&nbsp; I literally spent hours trying to use jQuery to properly attach an event to the iFrame, using different permutations of both .load() and .ready().&nbsp; For some reason these events were always attached instead to the parent page and only ever fired when the parent page was first ready.&nbsp; Because of this and a couple other small issues that are likely due to my limited jQuery knowledge, I used a mix of jQuery and straight up javascript in my application.&nbsp; I also manually set the OnLoad event of the iFrame.&nbsp; The iFrame's onload event will fire the first time it's loaded, so I also created a boolean variable to track whether or not it's the first load.&nbsp; So let's get to the code.</p>
<h2>WrappedJsonResult</h2>
<pre class="brush: c-sharp;">using System.Web.Mvc;
namespace jQueryUploadSample
{
public class WrappedJsonResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Write("&lt;html&gt;&lt;body&gt;&lt;textarea id=\"jsonResult\" name=\"jsonResult\"&gt;");
base.ExecuteResult(context);
context.HttpContext.Response.Write("&lt;/textarea&gt;&lt;/body&gt;&lt;/html&gt;");
context.HttpContext.Response.ContentType = "text/html";
}
}
}</pre>
<p>As you can see, we're using a standard JsonResult and we're wrapping the output in an html document and a textarea.&nbsp; This will allow us to use jQuery to access the value of that textarea from our parent page.&nbsp; Next we'll work on our controller method that accepts the upload.</p>
<h2>UploadImage Controller Method</h2>
<p>To keep things simple we're just going to do everything in our controller method.&nbsp; We're also not going to do any validation, we're going to assume that every file uploaded is a jpg and we're going to return the path to the image as well as a status message.&nbsp; To demonstrate what to do in the event of an error, we will also return some status information in our&nbsp;JSON result.&nbsp; The beauty of dynamics in .NET and JSON allows us to do a lot of great stuff.&nbsp; For now, let's go ahead and create a controller method.&nbsp;</p>
<p>&nbsp;This method will accept an HttpPostedFile called "imagefile", save the file and return information back to our script.&nbsp; It will also assume that your images will be saved to a /Content/UserImages folder.&nbsp;We're going to generate a GUID to use as the image file name.&nbsp; Add the following method to a controller (preferrably one with the [Authorize] attribute set):</p>
<pre class="brush: c-sharp;"> [HttpPost]
public WrappedJsonResult UploadImage(HttpPostedFileWrapper imageFile)
{
if (imageFile == null || imageFile.ContentLength == 0)
{
return new WrappedJsonResult
{
Data = new
{
IsValid = false,
Message = "No file was uploaded.",
ImagePath = string.Empty
}
};
}
var fileName = String.Format("{0}.jpg", Guid.NewGuid().ToString());
var imagePath = Path.Combine(Server.MapPath(Url.Content("~/Content/UserImages")), fileName);
imageFile.SaveAs(imagePath);
return new WrappedJsonResult
{
Data = new
{
IsValid = true,
Message = string.Empty,
ImagePath = Url.Content(String.Format("~/Content/UserImages/{0}", fileName))
}
};
}</pre>
<p>Examining the code above you can see that we're first checking to see if an image was uploaded.&nbsp; If not, we're returning a WrappedJsonResult reporting the error to the calling script.&nbsp; If a file was there we generate a file name, save it to the server, and return the information back to the script.&nbsp; I should note that in the event of an error, it would not be necessary to return ImagePath and in the event of a succesful save you would not need to return Message.&nbsp; I've included it in both return values for completeness and so the javascript can assume that it's always there.</p>
<h2>Setting Up the HTML</h2>
<p>The next thing we need to do is setup the HTML for our form.</p>
<pre class="brush: c-sharp;">@using (Html.BeginForm("UploadImage", "YourController", FormMethod.Post,
new { enctype = "multipart/form-data", id="ImgForm",
name="ImgForm", target="UploadTarget" }))
{
&lt;h3&gt;Upload Image&lt;/h3&gt;
&lt;input type="file" name="imageFile" /&gt;
&lt;input type="button" value="Save Image" onclick="UploadImage()" /&gt;
}
&lt;iframe id="UploadTarget" name="UploadTarget" onload="UploadImage_Complete();" style="position: absolute; left: -999em; top: -999em;"&gt;&lt;/iframe&gt;
&lt;div id="Images"&gt;&lt;/div&gt;
</pre>
<p>The name of your file input "imageFile" must match the parameter name of your UploadImage method.&nbsp; Make sure you replace "YourController" with the name of the controller UploadImage is in.&nbsp; You'll also notice that I've positioned the iFrame off of the screen rather than simply changing it's display property via CSS.&nbsp; Some browser versions (I believe older versions of Firefox and Safari) do not always play nice with hidden iFrames so I've just positioned it off the page instead.&nbsp; We've also added an "Images" div that we'll use to shovel the images in after they've been uploaded.</p>
<p>Now all that's left to do is setup our Javascript.&nbsp; We'll need an UploadImage() method that will handle uploading the image and an UploadImage_Complete method that will fire when the iFrame has finished loading.</p>
<h2>Setting Up the Javascript</h2>
<p>The first thing we need to do is include a version of jQuery.&nbsp; Since I'm writing an MVC application, I've chosen to use Microsoft's CDN and I'm using jQuery 1.7.&nbsp; Add the following line to the HEAD section of your page:</p>
<pre style="background: white; color: black; font-family: Consolas;"><span style="color: blue;">&lt;</span><span style="color: maroon;">script</span>&nbsp;<span style="color: red;">src</span><span style="color: blue;">=</span><span style="color: blue;">"http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js"</span>&nbsp;<span style="color: red;">type</span><span style="color: blue;">=</span><span style="color: blue;">"text/javascript"</span><span style="color: blue;">&gt;&lt;/</span><span style="color: maroon;">script</span><span style="color: blue;">&gt;</span>
</pre>
<p>Now we can start&nbsp;creating our javascript to handle our form posts.&nbsp; The UploadImage() method isn't absolutely necessary since all our example does is post the form, however if you wanted to display a busy indicator it would be a good place to do it.&nbsp; Here we're just going to create a global variable that tells whether or not we're on the first load of the iFrame and the function to upload the image:</p>
<pre class="brush: js;">var isFirstLoad = true;
function UploadImage()
{
$("#ImgForm").submit();
}</pre>
<p>Now the form is setup to post to our iFrame.&nbsp; All we have to do is retrieve the result of the post and display the new image.&nbsp; Here is the code to retrieve the result and handle the completion of the image upload:</p>
<pre class="brush: js;">function UploadImage_Complete()
{
//Check to see if this is the first load of the iFrame
if (isFirstLoad == true)
{
isFirstLoad = false;
return;
}
//Reset the image form so the file won't get uploaded again
document.getElementById("ImgForm").reset();
//Grab the content of the textarea we named jsonResult . This shold be loaded into
//the hidden iFrame.
var newImg = $.parseJSON($("#UploadTarget").contents().find("#jsonResult")[0].innerHTML);
//If there was an error, display it to the user
if (newImg.IsValid == false)
{
alert(newImg.Message);
return;
}
//Create a new image and insert it into the Images div. Just to be fancy,
//we're going to use a "FadeIn" effect from jQuery
var imgDiv = document.getElementById("Images");
var img = new Image();
img.src = newImg.ImagePath;
//Hide the image before adding to the DOM
$(img).hide();
imgDiv.appendChild(img);
//Now fade the image in
$(img).fadeIn(500, null);
}</pre>
<h2>Conclusion</h2>
<p>And that's it.&nbsp;&nbsp;Technically there wasn't a lot of jQuery work done, however we did demonstrate some of it and we can upload a file to our server&nbsp;in an&nbsp;AJAXy fashion.&nbsp;</p>
<h2>Downloads</h2>
<p>You can download&nbsp;the Visual Studio 2010 Solution here:&nbsp;<br /><a href="https://www.dustinhorne.com/files/AjaxFileUploadDemo.zip">AjaxFileUploadDemo.zip</a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>https://www.dustinhorne.com/post/2011/11/16/AJAX-File-Uploads-with-jQuery-and-MVC-3
nebraskadev@gmail.comhttps://www.dustinhorne.com/post/2011/11/16/AJAX-File-Uploads-with-jQuery-and-MVC-3#commenthttps://www.dustinhorne.com/post.aspx?id=f7e59caa-c540-4c92-8988-97485b849cc5Wed, 16 Nov 2011 09:32:00 -0700jQueryASP .NET MVCDustinhttps://www.dustinhorne.com/pingback.axdhttps://www.dustinhorne.com/post.aspx?id=f7e59caa-c540-4c92-8988-97485b849cc516https://www.dustinhorne.com/trackback.axd?id=f7e59caa-c540-4c92-8988-97485b849cc5https://www.dustinhorne.com/post/2011/11/16/AJAX-File-Uploads-with-jQuery-and-MVC-3#commenthttps://www.dustinhorne.com/syndication.axd?post=f7e59caa-c540-4c92-8988-97485b849cc5