Showing posts with label ASP.Net MVC. Show all posts
Showing posts with label ASP.Net MVC. Show all posts

Wednesday, 18 January 2017

Create a File upload html page in asp.net MVC and upload a file to controller action with mapping the model using AutoMapper

In this post we are going to see how to create a File upload html page in asp.net MVC and map the model using the Automapper.












For this First we have to create a empty ASP.Net MVC application, then install the automapper using nuget, Now we have to create the models, then create the ViewModel, later we have to map the property of this two classes using the automapper


    public class PostViewModel
    {
        public HttpPostedFileBase File { set; get; }

        public string PostTitle { set; get; }

        public string PostDescription { set; get; }
    }

    public class PostModel
    {
        public string Title { set; get; }

        public string Description { set; get; }

        public string Details
        {
            get { return string.Format("{0},{1}", Title,
                    Description.Substring(10) + "..."); }
        }

        public string imageUrl { set; get; }

    }


Now create a Profile for this model mappings, then define the properties and there mappings, then create a Configuration class where we can initialize the profile.


    public class PostToViewModelMappingProfile:Profile
    {
        public override string ProfileName
        {
            get
            {
                return "PostToViewModelMapping";
            }
        }

        protected override void Configure()
        {
            this.CreateMap<PostViewModel, PostModel>()
                .ForMember(p => p.Title, pvm => pvm.MapFrom(vm => vm.PostTitle))
                .ForMember(p => p.Description, pvm => pvm.MapFrom(vm => vm.PostDescription));
        }

    }



    public class AutoMapperConfiguration
    {
        public static void Configure()
        {
            AutoMapper.Mapper.Initialize(cf => {
                cf.AddProfile<PostToViewModelMappingProfile>();
            });
        }
    }


Above Configuration needs to be called from app.start file.

    public partial class Startup
    {       
        public void ConfigureAuth(IAppBuilder app)
        {
              AutoMapperConfiguration.Configure();

        }

    }




Now we have to create the controller with a action upload where we have input as model with type PostViewModel , then save the file using the property File which is a type of HttpPostedFileBase

Then called the Mapper.Map for copy the values from input model to PostModel


        [HttpPost]
        public ActionResult Upload(PostViewModel model)
        {
            var file = model.File;
            string filename = Path.GetFileName(model.File.FileName);
            string path = Path.Combine(Server.MapPath("~/img/"), filename);
            model.File.SaveAs(path);
            var postmodel = Mapper.Map<PostViewModel, PostModel>(model);
            postmodel.imageUrl = filename;
            return View(postmodel);

        }


After Create this Now create a view for upload.cshtml

@model BaseWebApp.Models.PostModel
@{
    ViewBag.Title = "Upload";
}

<div class="panel panel-default panel-success" style="width:700px;">
    <div class="panel-body">
        <img class="left"  src="../../img/@Model.imageUrl"/>
        <p style="font-weight:bold">@Model.Title</p>
        <p>@Model.Description</p>
    </div>

</div>



Now we create a core part which will upload a file from html to MVC controller.In this we are creating a Form which targets the enctype multipart/form-data , now you may have question how the html controls value will be mapped to model in controller action.


<div style="marin:20px;padding:20px">
    @using(Html.BeginForm("Upload","Home",FormMethod.Post,
        new { enctype = "multipart/form-data", @class = "form-inline" }))
    {
        <div class="form-group">
            <label for="file">File :</label>
            <input type="file" name="file" class="form-control"
                   placeholder="Select image .."/>
        </div>
        <div class="form-group">
            <label class="sr-only" for="postTitle">Username :</label>
            <input type="text" name="postTitle" class="form-control"
                    placeholder="Post Title" />
        </div>
        <div class="form-group">
            <label class="sr-only" for="postDescription">Description :</label>
            <input type="text" name="postDescription" class="form-control"        
                   title="description" placeholder="Post Description" />
        </div>
        <button type="submit" class="btn btn-success">Upload</button>
    }

</div>



index.cshtml












upload.cshtml






























From this post you can learn how to create a fileupload html page in asp.net mvc and map the model using the Automapper.



Saturday, 11 June 2016

View or Download PDF files in ASP.NET MVC


In this post we are going to see how to view or download PDF files in ASP.NET MVC, Normally in applications we have reports and files to be viewed in PDF format, sometimes we need to download the files, Now we are going to see various ways of viewing a PDF file and downloading option in MVC.

In ASP.NET MVC we have action result which is used to server the file content to the client browser,  FilePathResult is used to display the content of the PDF file in the browser.

Steps to do:
1. Create a MVC Project 
2. Create a Folder PdfFiles
3.  Place your PDF files
4. Start writing your Controller logic.

Here for View , we will do three different ways one with passing File path, another one with passing File Content, another one is embedding as inline PDF using Ajax.

Controller Logic:

HomeController


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ViewPDF.Models;

namespace ViewPDF.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            FileInfo []info = new DirectoryInfo(Server.MapPath("/PdfFiles")).GetFiles();
            return View(info.ToList());
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public FileResult ViewPDF(string name)
        {
            return File(name, "application/pdf");
        }

        public FileResult DownloadPDF(string name)
        {
           
            byte[] pdfByte = FileContent(name);
            return File(pdfByte, "application/pdf", name.Substring(name.LastIndexOf("\\")+1));
        }

        public FileResult PDFDisplay(string name)
        {           
            byte[] pdfByte = FileContent(name);
            return File(pdfByte, "application/pdf");
        }

        public PartialViewResult PDFInlineView(string name)
        {            
            PDFModel model = new PDFModel() {FilePath = name };
            return PartialView("PDFView",model);
        }

        private  byte[] FileContent(string path)
        {            
            FileStream stream = null;           
            try
            {
                stream = System.IO.File.OpenRead(path);
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, Convert.ToInt32(stream.Length));
                return bytes;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }

        }

    }
}



create a model class to pass the model to async operation, we need a virtual path to process in async operation
 public class PDFModel
    {
        private string _virtualFilepath;

        public string FilePath {
            set {
               _virtualFilepath= "../PdfFiles/" + 
                 value.Substring(value.LastIndexOf("\\") + 1  );
            }
            get { return _virtualFilepath; }
        }
    }


HTML Logic:

index.cshtml


@using System.IO

@{
    ViewBag.Title = "Home Page";
}

@model IEnumerable<FileInfo>


<div class="panel">
   
    <table class="table table-condensed">
        <thead>
            <tr>
                <td>FileName</td>
                <td>View</td>
                <td>Download</td>
                <td>View2</td>
                <td>Inline view</td>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {


                <tr class="">
                    <td class="col-lg-1"> 
                       <label>@item.Name <span>@item.Length</span></label>
                    </td>
                    <td class="col-lg-1">
                      <button class="btn btn-info btn-sm"                                                             @Html.ActionLink("View""ViewPDF"new { name = item.FullName })
                      </button>
                   </td>
                    <td class="col-lg-1">
                      <button class="btn btn-info btn sm">
                    @Html.ActionLink("Download""DownloadPDF"new { name = item.FullName })
                      </button>
                    </td>
                    <td class="col-lg-1">
                     <button class="btn btn-info btn-sm">                                                         @Html.ActionLink("View2""PDFDisplay"new { name = item.FullName })
                     </button>
                    </td>
                    <td class="col-lg-1">
                      <button class="btn btn-info btn-sm">                                                           @Ajax.ActionLink("InlineView""PDFInlineView"
                        new { name = item.FullName }, 
                        new AjaxOptions { UpdateTargetId = "pdfInline" })
                      </button>    
                    </td>
                </tr>
            }
        </tbody>

    </ul>

   
    <div id="pdfInline">

    </div>

</div>





pdfview.cshtml


@model ViewPDF.Models.PDFModel

<h4>PDF inline View....</h4>


<object style="height:500px;width:800px" data="@Model.FilePath" type="application/pdf">
    <p>It appears that you don't have Adobe Reader or PDF support in this web browser. 
    <a href="@Model.FilePath">Click here to download the PDF</a>. Or 
    <a href="http://get.adobe.com/reader/" target="_blank">click here to install Adobe Reader</a>.
    </p>
    <embed src="@Model.FilePath" type="application/pdf" />
</object>




Output:
                                             When you click the View button it will display the PDF file in the browser.





When you click the download button it will download the PDF files





If the browser doesn't support the inline view it will display a information like below





Ajax - Async operation of Viewing PDF as Inline



From this post you can learn how to create a application to View and Download PDF files in ASP.NET MVC