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.



2 comments:

  1. I love the blog. Great post. It is very true, people must learn how to learn before they can learn. lol i know it sounds funny but its very true. . .
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  2. Thank you for an additional great post. Exactly where else could anybody get that kind of facts in this kind of a ideal way of writing? I have a presentation next week, and I’m around the appear for this kind of data.
    python Training in Pune
    python Training in Chennai
    python Training in Bangalore

    ReplyDelete