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

Tuesday, November 14, 2017

File Upload Control Model MVC C#


TWO File Upload Control in Model With Custom Attribute -Data Annotations


For Understand file upload control in MVC C# (.Net) We are taking example of Upload Profile Pic & Covert Photo. We are defining "HttpPostedFileBase" in Model. Here "FileSize" and "FileTypes" are custom attributes we will create custom attibutes in step2. so don't worry if it's give compile time error.

Step 1 :  Create A Model  


public class FileUploadModel
    {
        [Required(ErrorMessage = "Please Choose Profile Pic")]
        [FileSize(102400)]
        [FileTypes("jpg,jpeg,png")]
        public HttpPostedFileBase ProfilePic { get; set; }

        [Required(ErrorMessage = "Please Choose Cover Photo")]
        [FileSize(1002400)]
        [FileTypes("jpg,jpeg,png")]
        public HttpPostedFileBase CoverPhoto { get; set; }
    }


Step 2 :  Create A Class for  Custom Validation Data Annotation Attribute for Validate Image File.


In above model we have used two custom attribute for validate image size and image type.Validation in MVC can be done using Data Annotations that are applied to both the client and server side, so Create one folder "Attributes" and define below mention class in it.  

Add reference of below class in model defined in step1.


public class FileSizeAttribute : ValidationAttribute
        {
            private readonly int _maxSize;

            public FileSizeAttribute(int maxSize)
            {
                _maxSize = maxSize;
            }

            public override bool IsValid(object value)
            {
                if (value == null) return true;

                return (value as HttpPostedFileBase).ContentLength <= _maxSize;
            }

            public override string FormatErrorMessage(string name)
            {
                return string.Format("The file size should not exceed {0}", _maxSize);
            }
        }


        public class FileTypesAttribute : ValidationAttribute
        {
            private readonly List<string> _types;

            public FileTypesAttribute(string types)
            {
                _types = types.Split(',').ToList();
            }

            public override bool IsValid(object value)
            {
                if (value == null) return true;

                var fileExt = System.IO.Path.GetExtension((value as HttpPostedFileBase).FileName).Substring(1);
                return _types.Contains(fileExt, StringComparer.OrdinalIgnoreCase);
            }

            public override string FormatErrorMessage(string name)
            {
                return string.Format("Invalid file type. Only the following types {0} are supported.", String.Join(", ", _types));
            }
        }


Step 1 :  Create File Upload Controller & View 


We will store profile pic and cover photo in two different directory. 

Controller


public class FileUploadController : Controller
    {
        // GET: FileUpload
        public ActionResult Index()
        {

            return View();
        }

        // HTTP Post Method
        [HttpPost]
        public ActionResult Index(FileUploadModel objfileModel)
        {

            if (ModelState.IsValid)
            {
                if (objfileModel != null && objfileModel.ProfilePic != null && objfileModel.ProfilePic.ContentLength > 0)
                {
                    var ProfilePicName = Path.GetFileName(objfileModel.ProfilePic.FileName);
                    if (!Directory.Exists(Server.MapPath("~\\Uploads\\ProfilePic\\")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~\\Uploads\\ProfilePic\\"));
                    }
                    objfileModel.ProfilePic.SaveAs(Server.MapPath("~\\Uploads\\ProfilePic\\" + ProfilePicName));

                }

                if (objfileModel != null && objfileModel.CoverPhoto != null && objfileModel.CoverPhoto.ContentLength > 0)
                {
                    var CoverPicName = Path.GetFileName(objfileModel.CoverPhoto.FileName);

                    if (!Directory.Exists(Server.MapPath("~\\Uploads\\CoverPhoto\\")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~\\Uploads\\CoverPhoto\\"));
                    }
                    objfileModel.CoverPhoto.SaveAs(Server.MapPath("~\\Uploads\\CoverPhoto\\" + CoverPicName));

                }
                ViewBag.Message = "Upload successfully";
                return RedirectToAction("Index");
            }
            else
            {

                ViewBag.Message = "Error during Upload";
                return View();
                
            }

        }
        
    }


Views


@model  WebApplication1.Models.FileUploadModel
@{
    Layout = null;
}

<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<style>
    .input-validation-error {
        border: 1px solid #ff0000;
        background-color: #e96363;
    }

     .field-validation-error {
        color: #ff0000;
    }

    .field-validation-valid {
        display: none;
    }

    .input-validation-error {
        border: 1px solid ##ff0000;
        background-color: ##FF0000;
    }

    .validation-summary-errors {
        font-weight: bold;
        color: #ff0000;
    }

    .validation-summary-valid {
        display: none;
    }

</style>

<div class="container">
    <h2>File Upload Control Using Strongly Bind Model</h2>
    @using (Html.BeginForm("Index", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <span>@ViewBag.Message</span>
        <form>
            <div class="form-group">
                <span>@Html.LabelFor(m => m.ProfilePic)  &nbsp;</span>
                @Html.TextBoxFor(m => m.ProfilePic, new { type = "file" ,@class="custom-file-input" })
                @Html.ValidationMessageFor(m => m.ProfilePic) <br />
            </div>
            <div class="form-group">
                <span>@Html.LabelFor(m => m.CoverPhoto) &nbsp;</span>
                @Html.TextBoxFor(m => m.CoverPhoto, new { type = "file" })
                @Html.ValidationMessageFor(m => m.CoverPhoto)
            </div>


            <input type="submit" value="Upload" class="btn btn-default" />
        </form>
    }


</div>








Tuesday, January 5, 2016

Avoid Redirect to Account/Login?ReturnUrl=%2f

Hello Guys,

If your using form authentication then you may face redirection issue on your home page of website.

If you have a login button on home page and if you want to authenticate user only after click on login button.

So for this you need to follow below steps.

In web.config file add below key AppSetting.

<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>


Second case.

 you have to Assign Default page in route table.


Sunday, December 6, 2015

AnglularJS WIth Webservice IN MVC


$http Post Method With And Withour parameter



<!doctype html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js"></script>
 
    <script>
        var mainApp = angular.module("mainApp", []);
        mainApp.controller('tripController', function ($scope, $http) {
            var parameter = JSON.stringify('{ClientId:130}');
            $http({
                method: 'POST',
                data: { ClientId: "130" },
                url: 'http://localhost/msr/ContactService.svc/GetContact'
            })
       .success(function (data) {
           $scope.contacts = data;
       });
        });


        mainApp.controller('TimeZoneController', function ($scope, $http) {
            alert("In");
            $http({
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                url: 'http://localhost/msr/Common.svc/GetTimeZone'
            })
        .success(function (data) {
            $scope.timezones = data;
        });
        });
    </script>

</head>

<body>
    <h2>AngularJS Sample Application</h2>
    <div ng-app="mainApp">
        <div ng-controller="tripController">
            <table>
                <tr>
                    <td>ClientId</td>
                    <td>ContactId</td>
                    <td>Names</td>
                    <td>Email</td>
                </tr>
                <tr ng-repeat="contact in contacts.lstContact">
                    <td>{{ contact.ClientId }}</td>
                    <td>{{ contact.ContactId }}</td>
                    <td>{{ contact.Name}}</td>
                    <td>{{ contact.EmailOrMobile }}</td>

                </tr>
            </table>
        </div>


        <h2>Time Zone</h2>
        <div ng-controller="TimeZoneController">
            <table>
                <tr>
                    <td>Text</td>
                    <td>Value</td>
                </tr>
                <tr ng-repeat="timezone in timezones.GetTimeZoneResult.lstTimezone">
                    <td> {{ timezone.Text }} </td>
                    <td> {{ timezone.Value }} </td>
                </tr>

            </table>

        </div>
    </div>

</body>

</html>




Featured Post