How to upload file on asp.net mvc ?


FileUpload

So many time, beginner in asp.net mvc will ask this question. I will show on basic demo for this functionality.

Step 1: Create the Index view like this

@{
    ViewBag.Title = "Index";
}


@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    <label for="file">Upload Image:</label>
    <input type="file" name="file" id="file" /><br><br>
    <input type="submit" value="Upload Image" />
    <br><br>
    @ViewBag.Message
}

Step 2: Write the code in Home Controller for file upload like this

using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace ImageUpload_MVC.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult FileUpload(HttpPostedFileBase file) 
        {
            if (file != null && file.ContentLength > 0)
                try
                {
                    string path = Path.Combine(Server.MapPath("~/Images"),
                                               Path.GetFileName(file.FileName));
                    file.SaveAs(path);
                    ViewBag.Message = "File uploaded successfully";
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            else
            {
                ViewBag.Message = "You have not specified a file.";
            }
            return View("Index");
            //return RedirectToAction("Index", "Home");
        }
    }
}
 

Note: Don’t forget to keep Images folder in application

Summary:

We show the basic file upload functionality in asp.net MVC.

How to implement multiple submit button in asp.net MVC ?


In Asp.net MVC there are so many ways to implement the multiple submit button in single view.
I have already written one post using attribute-based solution

But there are still so many other approaches to do this task like

1. Using Multiple button with different Name
2. Using Multiple button with Same Name
3. using HTML 5 Foraction and Formmethod
4. using using Jquery Click event

Here I am going to show all the 4 approaches in single view and controller for sake of simplicity

Step 1: Create the Emp class in Model folder like this

namespace MultipleSave.Models
{
    public class Emp
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }
        public string  EmailId { get; set; }
    }
}

Step 2: Keep the all UI related code in Index view

@model MultipleSave.Models.Emp

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>


@using (Html.BeginForm("ProcessForm","Home",FormMethod.Post)) 
{
    <b>Method 1</b>
    @Html.AntiForgeryToken()

    @Html.EditorForModel()
    <br />
    <input type="submit" name="save" value="Save" />
    <input type="submit" name="cancel" value="Cancel" />
    <br />
    @ViewBag.msg

}
<br />

@using (Html.BeginForm("SaveData", "Home", FormMethod.Post))
{
    <b>Method 2</b>
    @Html.AntiForgeryToken()

    @Html.EditorForModel()
    <br />
    <input type="submit" name="submit" value="Save" />
    <input type="submit" name="submit" value="Cancel" />
    <br />
    @ViewBag.msg1

}

<br />

@using (Html.BeginForm())
{
    <b>Method 3 using HTML 5 Foraction and Formmethod</b>
    @Html.AntiForgeryToken()

    @Html.EditorForModel()
    <br />
    <input type="submit" name="save" value="Save"
           formaction="SaveForm" formmethod="post" />
    <input type="submit" name="cancel" value="Cancel"
                   formaction="CancelForm" formmethod="post" />
    <br />
    @ViewBag.msg2

}

<br />

@using (Html.BeginForm())
{
    <b>Method 4 using Jquery</b>
    @Html.AntiForgeryToken()

    
    <br />
    @Html.EditorForModel()
    <br />
    <input type="submit" id="save" value="Save" />
    <input type="submit" id="cancel" value="Cancel" /><br />
                @ViewBag.msg3

}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(document).ready(function () {

        $("#save").click(function () {
            $("form").attr("action", "/home/Saveform1");
        });

        $("#cancel").click(function () {
            $("form").attr("action", "/home/Cancelform1");
        });

    });
</script>

Step 3: Write the C# code in Home Controller like this


using MultipleSave.Models;
using System.Web.Mvc;

namespace MultipleSave.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        //Method 1 Multiple button with different Name
        [HttpPost]
        public ActionResult ProcessForm(Emp obj,string save,string cancel)
        {
            if(!string.IsNullOrEmpty(save))
            {
                ViewBag.msg = "Emp saved successfully";
            }
            if(!string.IsNullOrEmpty(cancel))
            {
                ViewBag.msg = "The operation was cancelled";
            }
            return View("Index", obj);
        }

        // Method 2 Multiple button with Same Name
        [HttpPost]
        public ActionResult SaveData(Emp obj, string submit)
        {
            switch (submit)
            {
                case "Save":
               ViewBag.msg1 = "Emp saved successfully";
                    break;
                case "Cancel":
                    ViewBag.msg = "The operation was cancelled";
                    break;
            }
            return View("Index", obj);
        }

        //Method 3: using HTML 5 features
        [HttpPost]
        public ActionResult SaveForm(Emp obj)
        {
            ViewBag.msg2 = "Emp saved successfully";
            return View("Index", obj);
        }

        //Method 3: using HTML 5 features
        [HttpPost]
        public ActionResult CancelForm(Emp obj)
        {
            ViewBag.msg2 = "The operation was cancelled";
            return View("Index", obj);
        }

        //Method 4: using Jquery
        [HttpPost]
        public ActionResult SaveForm1(Emp obj)
        {
            ViewBag.msg3 = "Emp saved successfully";
            return View("Index", obj);
        }

        //Method 4: using Jquery
        [HttpPost]
        public ActionResult CancelForm1(Emp obj)
        {
            ViewBag.msg3 = "The operation was cancelled";
            return View("Index", obj);
        }

    }
}

Summary:
Here we show that how to handle the multiple submit button in single view with so many ways.

Asp.net MVC Version History Details


Asp.net MVC has shipped to public with .net f/w 3.5 i.e. with VS 2008 and after onward so much new features has been added.

Now asp.net mvc has been matured and most powerful technology to develop any web application. So just we will see the main features of each version

MVC 1.0
1. Released date: 13-Mar-2009
2. Came with .net f/w 3.5 and VS 2008
3. MVC architecture with Web form engine
4. Routing concept implemented first time.
5. HTML Helpers
6. Ajax Helpers
7. Auto binding

MVC 2.0
1. Area
2. Asynchronous Controller
3. Html helper method with lambda expression
4. Data Annotations attributes
5. Client Side Validation
6. Custom Template
7. Scaffolding
8. Came with VS 2008 Sp1 in 10 mar-2010.

MVC 3.0
1. Unobtrusive JavaScript validation
2. Razor view engine
3. Global Filter
4. Remote Validation
5. Dependency resolver for IOC
6. ViewBag
7. Came with VS 2010 in 13-Jan-2011

MVC 4.0
1. Mobile project template
2. Bundling and magnification
3. Support for Window Azure SDK
4. Came with .net F/w 4.0 and 4.5 in 15-Aug-2012

MVC 5.0
1. It came with VS 2013 in Oct 2013
2. One Asp.net
3. New Web Project experience
4. Asp.net Identity
5. Bootstrap Template
6. Attribute routing
7. Asp.net Scaffolding
8. Authentication Filter
9. Filter Overrides.

MVC 6.0
1. ASP.NET MVC and Web API have been merged in to one.
2. Dependency injection is inbuilt and part of MVC.
3. Side by side – deploy the runtime and framework with your application
4. Everything packaged with NuGet, Including the .NET runtime itself.
5. New JSON based project structure.
6. No need to recompile for every change. Just hit save and refresh the browser.
7. Compilation done with the new Roslyn real-time compiler.
8. vNext is Open Source via the .NET Foundation and is taking public contributions.
9. vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.
10. It came with VS 2015

What is the use of this Keyword in C# ?


This keyword is used to refer the current instance of class. It is also used as modifier of the first parameter of an extension method.

The following are the common use of this Keyword
1. To qualify the member hidden by similar name.
2. To pass object as parameter to other methods

Let see one simple example for this

using System;

namespace This_Keyword_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create object
            Employee objEmp = new Employee("Chandradev","Prasad");
            //Display result
            objEmp.printEmployee();
            Console.ReadKey();
        }
    }
    class Tax
    {
       public static decimal CalcTax(Employee E)
        {
            return 0.08m * E.Salary;
        }
    }
    class Employee
    {
        private string firstName;
        private string lastName;
        private decimal salary = 5000m;
        public  Employee(string firstName,string lastName)
        {
            this.firstName = firstName;
            this.lastName = lastName;
        }   

        public void printEmployee()
        {
            Console.WriteLine("FirstName: {0}\nLastName: {1}",firstName,lastName);
            Console.WriteLine("Taxes: {0:C}",Tax.CalcTax(this));
        }
        public decimal Salary
        {
            get { return salary; }
        }

    }
}

This_Keyword
Explanation:

In the above example, this.name and this.alias is representing the private string value of Employee class
And in Tax.calcTax(this) , we are passing the class objet of Employee as parameter to other CalcTax method of Tax class.

Let see one more simple example of this Keyword

using System;

namespace This_Keyword
{
    class Program
    {
        static void Main(string[] args)
        {
            Test obj = new Test();
            obj.Get();
        }
    }
    class Test
    {
        int a=10,b=20;
        public void Get()
        {
            int a = 30, b = 40;
            Console.WriteLine("The class variable are a={0},b={1}", this.a, this.b);
            Console.WriteLine("The Local Variable are a={0},b={1}",a,b);
            Console.ReadLine();
        }

    }
}

ThisKey

Explanation:

In the above example we are differentiating the class variable i.e. global variable and local variable when both the variable names are same. If we will use the this keyword then it will show only class variable i.e. Global variable.

There are several usages of this keyword in C#.

1. To qualify members hidden by similar name
2. To have an object pass itself as a parameter to other methods
3. To have an object return itself from a method
4. To declare indexers
5. To declare extension methods
6. To pass parameters between constructors
7. To internally reassign value type (struct) value.
8. To invoke an extension method on the current instance
9. To cast itself to another type
10. To chain constructors defined in the same class

Named and optional Parameter in C#


Named and optional parameters are the one of the new features of C# 4.0. This feature allows developers to have an option to create named and optional parameters in a method.

Named Parameter

Now let see the example of Named Parameter:

NamedParameter

Complete C# code

using System;

namespace Named_OptionalParameter
{
    class Program
    {
        static void Main(string[] args)
        {
            var objPrice = new PriceClass();
            //Traditional approach to Call the method
            Console.WriteLine(objPrice.CalculatePrice(10,100,false));
            // Using Named parameter approach to call the method
            Console.WriteLine(objPrice.CalculatePrice(EliteMember:false,quantity:10,price:100));
            Console.ReadLine();
        }
    }
    public class PriceClass
    {
        public double CalculatePrice(int quantity,double price, bool EliteMember)
        {
            if (EliteMember)
            {
                return quantity * price - 10;
            }
            else
                return quantity * price;
        }
    }
}

In the above code we saw that we have created the method to calculate price and we are passing the parameter as int, double, bool as parameter. But if we will not pass in this order it will through the exception upto C# 3.0. But from C# 4.0 there is not mandatory to pass parameter as same as method defined.

We can pass parameter as per as developer desire like this
// Using Named parameter approach to call the method

Console.WriteLine(objPrice.CalculatePrice(EliteMember:false,quantity:10,price:100));

Optional Parameter

Now let see the example of Optional parameter example

OptionalParameter

If you will see in the above example, CalculatePrice Method has two parameter i.e price and eliteMember. For that parameter it is not mandatory to pass the parameter. If we will not pass the parameter then it will take default value which one we have defined in parameter.

For example, if we have to override the optional value of method then this also possible, we have to just pass the desire value in parameter as shown in above image.

Summary:

We learned that what is the named and optional parameter in C#