Wednesday 26 September 2018

Display File Content From Selected file in IFrame in MVC using JQuery


            In this article I would like to know you about displaying the choosen file content from  file selected from choosen input control to show in iframe. For this take a controller named ‘FileContentController’ and add a view to the ‘index’ action method, as the code shown below :


FileContentController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC_DisplayFileContent_JQuery.Controllers
{
    public class FileContentController : Controller
    {
        // GET: FileContent
        public ActionResult Index()
        {
            return View();
        }
    }
}

Now add a view to the Index Action Method and add the below code to the Index.cshtml  :

Index.cshtml


iframe

Now update the RouteConfig file with the controller name as FileContent and action name as Index as shown below:
RouteConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MVC_DisplayFileContent_JQuery
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "FileContent", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

Now when we run the application , it shows the below error when inspect the code using F12
Uncaught ReferenceError: $ is not defined
    at (index):67
This is because the jquery supported file bundle script is in body tag after the footer tag, now we have to move to the head tag, then the error resolves.
After changing the jquery supported file bundle script from body tag to head, it displays as below and rectify the error $ is not defined



Output:

After running the application it shows as below :

Now choose file from the input control and the iframe looks as below :




No comments:

Post a Comment

Note: only a member of this blog may post a comment.