European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFEASP.NET :: Read Data From Excel File And Insert Into Database In ASP.NET MVC

clock January 18, 2022 08:01 by author Peter

I will show you how to connect to a Microsoft Excel workbook using the OLEDB.NET data provider, extract data and then insert it into the database table.

To begin with, we will create an ExcelToDatabase in Home Controller which returns a View. This method will return a View from where we have to upload the excel file. Now we will create another method ExcelToDatabase.  Now if we make a get request then ExcelToDatabase will be called and for post request, ExcelToDatabase will be called. The following is the code to read excel files.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.OleDb;
using System.IO;

namespace ExcelReadData
{
    public class HomeController : Controller
    {
        // GET: ClonePanel
        public ActionResult ExcelToDatabase()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ExcelToDatabase()
        {
            bool result = false;
            ViewBag.data = null;

            if (Request.Files["FileUpload1"].ContentLength > 0)
            {
                string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName).ToLower();
                string query = null;
                string connString = "";

                string[] validFileTypes = { ".xls", ".xlsx" };

                string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/Uploads"), Request.Files["FileUpload1"].FileName);
                if (!Directory.Exists(path1))
                {
                    Directory.CreateDirectory(Server.MapPath("~/Content/Uploads"));
                }
                if (validFileTypes.Contains(extension))
                {
                    if (System.IO.File.Exists(path1))
                    { System.IO.File.Delete(path1); }
                    Request.Files["FileUpload1"].SaveAs(path1);

                    //Connection String to Excel Workbook
                    if (extension.Trim() == ".xls")
                    {
                        connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path1 + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                        result = Service.ImportExceltoDatabase(path1, connString, userId);
                    }
                    else if (extension.Trim() == ".xlsx")
                    {
                        connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                        result = Service.ImportExceltoDatabase(path1, connString,userId);
                    }
                }
                else
                {
                    ViewBag.Error = "Please Upload Files in .xls, .xlsx or .csv format";
                }
            }
            if (result)
            {
                ViewBag.data = "Data Import Successfully from excel to database.";
            }
            else
            {
                ViewBag.data = "there is some issue while importing the Data.";
            }
            return View();
        }
    }
}


Here I have created a class Service that contains 1 method ConvertXSLXtoDataTable. The following is the code for the service class.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Data;

namespace ExcelReadData
{
    public class Service : IDisposable
    {
        #region **Private Variables**

        private TestDatabaseEntities _dbContext;

        #region **Constructor**

        public ImportExceltoDatabase()
        {
            _dbContext = new TestDatabaseEntities();
        }
        #endregion

        public bool ImportExceltoDatabase(string strFilePath, string connString)
        {
            bool result = false;
            OleDbConnection oledbConn = new OleDbConnection(connString);
            DataTable dt = new DataTable();
            try
            {
                oledbConn.Open();
                using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn))
                {
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    oleda.SelectCommand = cmd;
                    DataSet ds = new DataSet();
                    oleda.Fill(ds);

                    dt = ds.Tables[0];

                    if (dt.Rows.Count > 0)
                    {
                        table tblObj = new table();
                        foreach (DataRow row in dt.Rows)
                        {
                            tblObj.Name = row["Name"].ToString();
                            tblObj.Name = row["Address"].ToString();
                            tblObj.Salary = (int)row["Salary"];
                            tblObj.Age = (int)row["Age"];
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                result = false;
            }
            finally
            {
                oledbConn.Close();
            }
            return result;
        }
    }
}


Now we have to create a view that contains file upload control and a button. When a request for ExcelToDatabase of Home Controller is made, it will show file upload control with button control. When the user selects a file and presses the button it will make a post request to Home Controller and the ExcelToDatabase method will be called. The following is the Razor View for both requests.
@using (Html.BeginForm("ImportExcel", "ExcelToDB", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <table>
        <tr><td>Excel file</td><td><input type="file" id="FileUpload1" name="FileUpload1" /></td></tr>
        <tr><td></td><td><input type="submit" id="Submit" name="Submit" value="Submit" /></td></tr>
        <tr><td></td><td><lable>@(viewbag.data)</lable></td></tr>
    </table>
}



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Removing or Customizing View Engines in MVC

clock January 14, 2022 07:48 by author Peter

In this article, you will learn how to remove or customize View Engines not being used by an application.
If you are not using any view engine like ASPX View Engine, it is better to remove it to improve the performance, it is one of the many MVC performance tuning tips.
 
You might be wondering how it will improve the performance. Let's prove it by creating a new action method in a Home Controller, don't add a view for this action method now.
    public ActionResult Foo()  
    {  
         return View();  
    }   

Now, run the application and try navigating to "http://localhost:1212/Home/Foo". Here is what I received:

In the image above you can see how the MVC runtime is looking for an ASPX View Engine first and then the other view engines, which is still a default behavior.

You can control it from the Global.asax file by taking advantage of ViewEngines.Engines.Clear().

    protected void Application_Start()  
    {  
           ViewEngines.Engines.Clear();  
           ViewEngines.Engines.Add(new RazorViewEngine());  
           AreaRegistration.RegisterAllAreas();  
           WebApiConfig.Register(GlobalConfiguration.Configuration);  
           FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
           RouteConfig.RegisterRoutes(RouteTable.Routes);  
           BundleConfig.RegisterBundles(BundleTable.Bundles);  
           AuthConfig.RegisterAuth();  
     }


I highlighted the newly added code above. Now, run the application; you will see the following:


You will see that the MVC runtime successfully removed the ASPX View Engine but it is still looking for VBHTML Views.

You can also control it by customizing Razor View Engine to use only C# languages, by making some changes here:
    ViewEngines.Engines.Add(new RazorViewEngine());  

I highlighted the portion of code. This is actually calling the RazorViewEngine. RazorViewEngine() method internally that has support for both languages (C# and VB) by default. So, we need to override the default functionality by adding a class by the name "CustomRazorViewEngine" that inherits RazorViewEngine. The best place to add this class file is in the App_Start folder.
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    namespace MvcApplication1.App_Start  
    {  
        public class CustomRazorViewEngine : RazorViewEngine  
        {  
            public CustomRazorViewEngine()  
            {  
                base.AreaViewLocationFormats = new string[] {  
                    "~/Areas/{2}/Views/{1}/{0}.cshtml",  
                    "~/Areas/{2}/Views/Shared/{0}.cshtml"  
                };  
                base.AreaMasterLocationFormats = new string[] {  
                    "~/Areas/{2}/Views/{1}/{0}.cshtml",  
                    "~/Areas/{2}/Views/Shared/{0}.cshtml"  
                };  
                base.AreaPartialViewLocationFormats = new string[] {  
                    "~/Areas/{2}/Views/{1}/{0}.cshtml",  
                    "~/Areas/{2}/Views/Shared/{0}.cshtml"  
                };  
                base.ViewLocationFormats = new string[] {  
                    "~/Views/{1}/{0}.cshtml",  
                    "~/Views/Shared/{0}.cshtml"  
                };  
                base.PartialViewLocationFormats = new string[] {  
                    "~/Views/{1}/{0}.cshtml",  
                    "~/Views/Shared/{0}.cshtml"  
                };  
                base.MasterLocationFormats = new string[] {  
                    "~/Views/{1}/{0}.cshtml",  
                    "~/Views/Shared/{0}.cshtml"  
                };  
            }  
        }  
    }

Remember to use the System.Web.Mvc namespace. Now, in the Global.asax file add the following code:
    protected void Application_Start()  
    {  
        ViewEngines.Engines.Clear();  
        //ViewEngines.Engines.Add(new RazorViewEngine());  
        ViewEngines.Engines.Add(new CustomRazorViewEngine());  
        AreaRegistration.RegisterAllAreas();  
        WebApiConfig.Register(GlobalConfiguration.Configuration);  
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
        RouteConfig.RegisterRoutes(RouteTable.Routes);  
        BundleConfig.RegisterBundles(BundleTable.Bundles);  
        AuthConfig.RegisterAuth();  
    }


Remember to use the MvcApplication1.App_Start namespace to bring the class file created above into the Global.asax scope. Now, run the application, you will see the following output:


 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: MVC 4 WEB API .NET 4.5

clock January 5, 2022 08:52 by author Peter

We can expose a Web API from ASP.NET MVC4. It is a new feature from Microsoft. Clients can get data from a Web API in any format such as JSON, XML, JSONP, HTML and etc.

Now in this article, I am going to explain how to create a new Web API application and how to get data in various formats such as I mentioned above.
 
Purpose
HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.
 
The ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. In this tutorial, you will use the ASP.NET Web API to create a web API that returns a list of products.
 
The following are the steps to create a new Web API application in Visual Studio 2011.
 
Step 1: We will create a new project and the project type will be MVC4. See the following image:

Step 2: Now we will select a Web API template from the Project template Dialog window.

Step 3: Now we will create a Customer controller inside the Controller folder and will select an API controller with read/write actions.


Step 4: Now we will add an Entity Data Model for our Database where we have a Customer Table. You can see it in the attached Source code.
Step 5: It's time to modify our CustomerController to fetch and save data. See the code below.

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Net.Http;  
    using System.Web.Http;  
    using WEBAPISample45.Models;  
      
    namespace WEBAPISample45.Controllers {  
            public class CustomerController: ApiController {  
                private CompanyDBEntities context = new CompanyDBEntities();  
                // GET /api/customer  
                public IEnumerable < CustomerModel > Get() {  
                    IEnumerable < CustomerModel > list = null;  
                    list = (from c in context.Customers select new CustomerModel { Id = c.Id, Name = c.Name, Salary = (long) c.Salary }  
                        .AsEnumerable < CustomerModel > ();  
                        return list;  
                    }  
                    // GET /api/customer/5  
                    public CustomerModel Get(int id) {  
                        return (from c in context.Customers where c.Id == id select new CustomerModel {  
                            Id = c.Id,  
                                Name = c.Name,  
                                Salary = (long) c.Salary  
                        }).FirstOrDefault < CustomerModel > ();  
                    }  
                    // POST /api/customer  
                    public void Post(CustomerModel customer) {  
                        context.AddToCustomers(new Customer {  
                            Id = customer.Id, Name = customer.Name, Salary =  
                                customer.Salary  
                        });  
                        context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);  
                    }  

                    // PUT /api/customer/5  
                    public void Put(int id, CustomerModel customer) {  
                        var cust = context.Customers.First(c => c.Id == id);  
                        cust.Name = customer.Name;  
                        cust.Salary = customer.Salary;  
                        context.SaveChanges();  
                    }  
                    // DELETE /api/customer/5  
                    public void Delete(int id) {  
                        var cust = context.Customers.First(c => c.Id == id);  
                        context.Customers.DeleteObject(cust);  
                        context.SaveChanges();  
                    }  
                }  
            }

Step 7: Now we will run our application and see the output of the web API. Applications will run on the local server http://localhost:40683/ and you have to add the api/customer to the URL. So now your URL will be http://localhost:40683/api/customer. 


If you want to access a customer by id then you can use http://localhost:40683/api/customer/1 as the URL.

Now I am going to discuss a very important thing here. In the Web API, whatever format we use to send a request is the format of the returned response.
In the following JavaScript code, we are requesting data in JSON format. So the response will be returned in the JSON format. I will explain via Fiddler.

    <script type="text/javascript">  
        $(document).ready(function () {  
            $.ajax({  
      
                type: "GET",  
                url: "api/customer/1",  
                dataType: "json",  
                success: function (data) {  
                         alert(data);  
                }  
            });  
        });  
    </script>

XML
    <script type="text/javascript">  
        $(document).ready(function () {  
            $.ajax({  
      
                type: "GET",  
                url: "api/customer/1",  
                dataType: "xml",  
                success: function (data) {  
                         alert(data);  
                }  
            });  
        });  
    </script>


HTML

    <script type="text/javascript">  
        $(document).ready(function () {  
            $.ajax({  
      
                type: "GET",  
                url: "api/customer/1",  
                dataType: "html",  
                success: function (data) {  
                         alert(data);  
                }  
            });  
        });  
    </script>


If you see the above jQuery code we are only changing the DataType and we are not changing anything inside the Web API.
 
Now we will open Fiddler and see how we can get data in various formats.
 
Open Fiddler and go to the Composer tab. See the following screen:

In the above image, you will see the "Accept: text/html, text/html, */*; q=0.01" when we execute the query it will return a response in HTML format.

Now we will change the datatype to XML "Accept: application/xml, text/xml, */*; q=0.01" and will see the output in XML format.

Now we will change the datatype to JSON "Accept: application/json, text/javascript, */*; q=0.01"

And the output is in JSON format:




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Upload Files In ASP.NET MVC 5

clock December 17, 2021 08:38 by author Peter

Creating MVC Application
Let us implement these in a sample Application. Open Visual Studio. Go to File->New->Project. Give a suitable name to the Application. Click OK.

Select MVC Template. Click OK.

Adding Folder
We will add a folder to store the files in the application. Here, I have added a folder in the application.

Adding Controller
Let us add a controller. Right click on the Controller. Add->Controller.


Select MVC 5 Controller -Empty. Click Add.

Give a suitable name to the controller.

Write the following code in the controller.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FileUpload.Controllers
{
    public class UploadController: Controller
    {
        // GET: Upload
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult UploadFile()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
            try
            {
                if (file.ContentLength > 0)
                {
                    string _FileName = Path.GetFileName(file.FileName);
                    string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
                    file.SaveAs(_path);
                }
                ViewBag.Message = "File Uploaded Successfully!!";
                return View();
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return View();
            }
        }
    }
}

Adding View
Right click on UploadFileActionResult. Go to Add View.


Select the empty template. Click add.


Write the following code in the View.

@{
    ViewBag.Title = "UploadFile";
}
<h2>UploadFile</h2>
@using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new { enctype="multipart/form-data"}))
{
    <div>
        @Html.TextBox("file", "", new {  type= "file"}) <br />
        <input type="submit" value="Upload" />
        @ViewBag.Message
    </div>
}

Browse the Application
Let us now run the Application and check if it is working fine or not. Browse the Application.

Click upload. I have debugged the code to verify that the file gets uploaded successfully.


The code is working as per the expectations, as it hits the success message. We should get this message on the View, as well.


We will verify the file uploaded, by opening the folder in the Application’s directory.

Hence, we have just learned how to upload the file in ASP.NET MVC. I hope this post is useful to developers.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How Dapper Has Become King ORM In C#/MVC/.NET/.CORE?

clock December 15, 2021 06:34 by author Peter

What is Dapper?
    Dapper is a popular simple object mapping tool and nothing but an Object Relational Mapping(ORM).
    If you don't want to spend hours writing code to map query results from ADO.NET data readers to instances of those objects, Dapper is very useful for that.
    It not only allows developers to map relational database tables with .NET objects but also allows them to execute SQL queries in the database. It also gives flexibility as they can use tables, stored procedures, and views directly in the databases.

Is Dapper secure?
Dapper is the easiest and most secure way to buy and store all your digital assets from the groundbreaking apps and games powered by Flow. The Metaverse is here.

Is Dapper a micro ORM?
Dapper is a Mini micro ORM or a simple object mapper framework that helps to map the native query output to a domain class or a C# class. It is a high-performance data access system built by the StackOverflow team and released as open-source.
Here you can find all SO-thread

What is the fastest ORM?

I've created one example based on the example result I can say - Dapper is faster than SQL & Entity Framework.

Extension methods
Dapper extends the IDbConnection interface with these various methods,

    Execute
    Query:
    QuerySingle:
    QuerySingleOrDefault:
    QueryFirst:
    QueryFirstOrDefault:
    QueryMultiple:

Note
Here you can find the all the method details - Dapper methods

How does a dapper become a king?
Let's create one short example. Let us have one table “Employee” namely whatever you prefer.

 

Employee table

Column Type
ID Int NOT NULL - PK
Name NVARCHAR (50) NULL
Dob DATE NULL
Mob_no VARCHAR (15) NULL
Salary DECIMAL (18,12) NULL
Is_Approved BIT NULL

Note
In the above table you can see we used almost all data types on a regular basis.

Let’s create a table and fill the 1 Million record in the tables.

Table scripts

CREATE TABLE [dbo].[employee] (
    [Id]          INT           IDENTITY (1, 1) NOT NULL,
    [Name]        NVARCHAR (50) NULL,
    [Dob]         DATE          NULL,
    [Mob_no]      VARCHAR (15)  NULL,
    [Salary]      DECIMAL (18,12)  NULL,
    [Is_Approved] BIT           NULL,
    CONSTRAINT [PK_employee] PRIMARY KEY CLUSTERED ([Id] ASC)
);

Using the while loop fill the 1 Million data into the table.

Declare @Name nvarchar(50)
Declare @Dob Date
Declare @Mob_no VARCHAR(15)
Declare @Salary Decimal(18,12)
Declare @Is_Approved bit
DECLARE @counter int = 1


WHILE(@counter <= 1000000)
BEGIN
    SET @Name = CONCAT('Name_',@counter);
    SET @Dob = GETDATE()+@counter;
    SET @Mob_no = CONCAT('12345678_',@counter);
    SET @Salary = (10+@counter)
    SET @Is_Approved = 1

    INSERT INTO employee([Name],[Dob],[Mob_no],[Salary],[Is_Approved]) VALUES (@Name,@Dob,@Mob_no,@Salary,@Is_Approved);
    Set @counter = @counter+1;
END

Note
All records are inserted now to check the table data size.

You can check your table size using this store procedure.

exec sp_spaceused ‘employee’

SQL

Here you can see almost 67MB of data present in the table.

Another way you can find the storage of the data using an SQL server.

Steps
    Open your SQL Server
    Navigate you're working database
    Expand your tables folder -> Right-click on your table -> Click on properties menu at the last.
    Below popup is visible

*Let’s create a sample application

//Employee Class
public partial class employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Nullable<System.DateTime> Dob { get; set; }
        public string Mob_no { get; set; }
        public Nullable<decimal> Salary { get; set; }
        public Nullable<bool> Is_Approved { get; set; }
    }

//Home Controller
public class HomeController: Controller
    {
        private readonly string _connectionString = "{YOUR_CONNECTION}";
        SqlConnection con;
        SqlDataAdapter da;
        DataSet ds = new DataSet();
        List<employee> emp = new List<employee>();
        private demo_databaseEntities dd = new demo_databaseEntities();

        public ActionResult SQL()
        {
            Debug.Write("\nSQL Process Start => " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
            con = new SqlConnection(_connectionString);
            da = new SqlDataAdapter("select * from employee", con);
            da.Fill(ds);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                emp.Add(new employee()
                {
                    Id = Convert.ToInt32(dr["Id"]),
                    Name = Convert.ToString(dr["Name"]),
                    Dob = Convert.ToDateTime(dr["Dob"]),
                    Mob_no = Convert.ToString(dr["Mob_no"]),
                    Salary = Convert.ToDecimal(dr["Salary"]),
                    Is_Approved = Convert.ToBoolean(dr["Is_Approved"])
                });

            }
            Debug.Write("\nSQL Process End => " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
            //Some process for paging
            return Json(new { count = emp.Count(), data = emp.Take(10000)}, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Dapper()
        {
            Debug.Write("\nDapper Process Start => " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
            con = new SqlConnection(_connectionString);
            emp = con.Query<employee>("select * from employee").ToList();
            Debug.Write("\nDapper Process End => " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
            //Some process for paging
            return Json(new { count = emp.Count(), data = emp.Take(10000) }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult EntityFramework()
        {
            Debug.Write("\nEF Process Start => " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
            emp = dd.employees.ToList();
            Debug.Write("\nEF Process End => " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
            //Some process for paging
            return Json(new { count = emp.Count(), data = emp.Take(10000) }, JsonRequestBehavior.AllowGet);
        }
    }
*SQL


*Dapper


*Entity Framework




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Creating AutoComplete TextBox In ASP.NET MVC 5

clock December 8, 2021 08:20 by author Peter

One year back I wrote the following article: Creating AutoComplete Extender using ASP.NET  which has huge response. Currently it has 32 k views. So by considering same requirement in ASP.NET MVC I decided to write same type of article using ASP.NET MVC with the help of jQuery UI library. So let us implement this requirement step by step,

Step 1 - Create an ASP.NET MVC Application.
    "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
    Choose MVC empty application option and click on OK

Step 2 - Add model class.

Right click on Model folder in the created MVC application and add class named City and right the following line of code,

City.cs
    public class City  
      {  
          public int Id { get; set; }  
          public string Name { get; set; }  
      
      }


Step 3 Add user and admin controller
Right click on Controller folder in the created MVC application and add the controller class as,

Now after selecting controller template, click on add button then the following window appears,

Specify the controller name and click on add button, Now open the HomeController.cs file and write the following code into the Home controller class to bind and create the generic list from model class as in the following,

HomeController.cs
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web.Mvc;  
    using AutoCompleteInMVCJson.Models;  
    namespace AutoCompleteInMVCJson.Controllers  
    {  
        public class HomeController : Controller  
        {  
            // GET: Home  
            [HttpGet]  
            public ActionResult Index()  
            {  
                return View();  
            }  
            [HttpPost]  
            public JsonResult Index(string Prefix)  
            {  
                //Note : you can bind same list from database  
                List<City> ObjList = new List<City>()  
                {  
      
                    new City {Id=1,Name="Latur" },  
                    new City {Id=2,Name="Mumbai" },  
                    new City {Id=3,Name="Pune" },  
                    new City {Id=4,Name="Delhi" },  
                    new City {Id=5,Name="Dehradun" },  
                    new City {Id=6,Name="Noida" },  
                    new City {Id=7,Name="New Delhi" }  
      
            };  
                //Searching records from list using LINQ query  
                var Name = (from N in ObjList  
                                where N.Name.StartsWith(Prefix)  
                              select new { N.Name});  
                return Json(Name, JsonRequestBehavior.AllowGet);  
            }  
        }  
    }

In the above code, instead of going to database for records we are creating the generic list from model class and we will fetch records from above generic list.

Step 4
Reference jQuery UI css and js library reference as there are many ways to add the reference of jQuery library into the our project. The following are some methods:

    Using NuGet package manager , you can install library and reference into the project
    Use CDN library provided by Microsoft, jQuery, Google or any other which requires active internet connection.
    Download jQuery files from jQuery official website and reference into the project.

In this example we will use jQuery CDN library.

Step 5
Create jQuery Ajax function to call controller JSON action method and invoke autocomplete function,
    $(document).ready(function () {  
           $("#Name").autocomplete({  
               source: function(request,response) {  
                   $.ajax({  
                       url: "/Home/Index",  
                       type: "POST",  
                       dataType: "json",  
                       data: { Prefix: request.term },  
                       success: function (data) {  
                           response($.map(data, function (item) {  
                               return { label: item.Name, value: item.Name};  
                           }))  
      
                       }  
                   })  
               },  
               messages: {  
                   noResults: "", results: ""  
               }  
           });  
       })


To work above function don't forget to add the reference of the following jQuery CDN library as,
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>  
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Step 6
Add view named index and put above json function into the view. After adding code necessary files and logic the Index.cshtml will look like the following,

Index.cshtml
    @model AutoCompleteInMVCJson.Models.City  
    @{    
        ViewBag.Title = "www.hostforlife.eu";    
    }    
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">    
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>    
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>    
    <script type="text/javascript">    
        $(document).ready(function () {    
            $("#Name").autocomplete({    
                source: function (request, response) {    
                    $.ajax({    
                        url: "/Home/Index",    
                        type: "POST",    
                        dataType: "json",    
                        data: { Prefix: request.term },    
                        success: function (data) {    
                            response($.map(data, function (item) {    
                                return { label: item.Name, value: item.Name};    
                            }))    
        
                        }    
                    })    
                },    
                messages: {    
                    noResults: "", results: ""    
                }    
            });    
        })    
    </script>    
    @using (Html.BeginForm())    
    {    
        @Html.AntiForgeryToken()    
        
        <div class="form-horizontal">    
        
            <hr />    
        
            <div class="form-group">    
        
                <div class="col-md-12">    
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })    
        
                </div>    
            </div>    
        
        </div>    
    }    


Now run the application and type any word then it will auto populate the records which exactly start with first word as in the following screenshot,

If you want to auto populate the records which contain any typed alphabet,then just change the LINQ query as contain. Now type any word it will search as follows,

From all the above examples, I hope you learned how to create the auto complete textbox using jQuery UI in ASP.NET MVC.

Note

    For the detailed code, please download the sample zip file.
    Perform changes in Web.config file as per your server location.
    You need to use the jQuery library.

For all the examples above, we learned how to use jQuery UI to create auto complete textbox in ASP.NET MVC. I hope this article is useful for all readers. If you have a suggestion then please contact me.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: OAuth Token Based Authentication In ASP.Net Identity

clock November 30, 2021 06:17 by author Peter

In this article, I will explain how to generate 'Access Token' using credentials of 'Asp.net Identity' in 'ASP.Net MVC. Create a new project in Visual Studio.

Give connection string of your database. Register an Account.

Add the following three Nuget Packages to your project.

  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security.OAuth
  • Microsoft.Owin.Cors

Now, add TokenGenerating.cs class in the project.

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;

namespace SecureWebAPI.APIClasses
{
    public class TokenGenerating : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated(); //
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
            var result = userManager.Find(context.UserName, context.Password);
            //UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
            //var result = userManager.Find(context.UserName, context.Password);
            //UserManager holds data for register user.
            //context.UserName = Email of your registered user
            //context.Password = Password of your registered user
            if (result != null)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password is incorrect");
                return;
            }
        }
    }
}

Now add a new startup class for the token configuration file this class holds the information and setting of the token.

using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Threading.Tasks;
using System.Web.Http;

[assembly: OwinStartup(typeof(SecureWebAPI.APIClasses.AuthenticationStartupClass))]

namespace SecureWebAPI.APIClasses
{
    public class AuthenticationStartupClass
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var myProvider = new APIAUTHORIZATIONSERVERPROVIDER();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
        }
    }
}

Add new class for API Attributes

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

namespace SecureWebAPI.APIClasses
{
    public class APIAUTHORIZEATTRIBUTE : System.Web.Http.AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                base.HandleUnauthorizedRequest(actionContext);
            }
            else
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
            }
        }
    }
}

Change Global.asax file of your project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace SecureWebAPI
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configuration.EnsureInitialized();
        }
    }
}

Now change your WebApiConfig.cs file routemap

Your Project > App_Start folder > WebApiConfig.cs
routeTemplate: "api/{controller}/{action}/{id}",
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SecureWebAPI.Controllers
{
    public class UserController : ApiController
    {
        [AllowAnonymous]
        [HttpGet]
        public IHttpActionResult Get()
        {
            return Ok("Now server time is: " + DateTime.Now.ToString());
        }
        [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAuthenticate()
        {
            return Ok("Hello ");
        }
        [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAdmin()
        {
            return Ok("Helo User");
        }
    }
}

Add a ApiController .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SecureWebAPI.Controllers
{
    public class UserController : ApiController
    {
        [AllowAnonymous]
        [HttpGet]
        public IHttpActionResult Get()
        {
            return Ok("Now server time is: " + DateTime.Now.ToString());
        }
        [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAuthenticate()
        {
            return Ok("Hello ");
        }
        [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAdmin()
        {
            return Ok("Helo User");
        }
    }
}

Run your Project and leave it. Open Visual Studio, add a new console project. Add a new class to the console project.
class TokenInfo
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
}

Add function in Program.cs class.
public string GetAccessToken(string Email, string Password)
{
    string AccessToken = "";
    string responseFromServer = "";
    WebRequest request = WebRequest.Create("https://localhost:44370/token"); //your project url
    request.Method = "POST";
    string postData = "username=" + Email + "&password=" + Password + "&grant_type=password";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = byteArray.Length;
    System.IO.Stream dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();
    WebResponse response = request.GetResponse();
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    using (dataStream = response.GetResponseStream())
    {
        System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
        responseFromServer = reader.ReadToEnd();
        Console.WriteLine(responseFromServer);
    }
    TokenInfo myDeserializedClass = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenInfo>(responseFromServer);
    AccessToken = myDeserializedClass.access_token;

    response.Close();
    return AccessToken;
}

MainMethod
static void Main(string[] args)
{
    string Email = "Your Registered user Email";
    string Password = "Your Registered user Email";

    Program cls = new Program();
    string AccessToken = cls.GetAccessToken(Email, Password);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://localhost:44370/api/user/GetForAuthenticate"); //Your project Local host api url
    request.AutomaticDecompression = DecompressionMethods.GZip;
    request.Method = "GET";
    request.Headers.Add("Authorization", "Bearer " + AccessToken);
    using (System.Net.WebResponse GetResponse = request.GetResponse())
    {
        using (System.IO.StreamReader streamReader = new System.IO.StreamReader(GetResponse.GetResponseStream()))
        {
            dynamic jsonResponseText = streamReader.ReadToEnd();
        }
    }
    Console.ReadLine();
}

Run console project
If Credential is authenticated then an access token will also be generated.

Keep in mind Your Asp.net MVC project should be running during access token generating.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How To Implement AutoMapper In ASP.NET Core MVC Application?

clock November 23, 2021 06:04 by author Peter

In this demo, I will show how to utilize the Automapper library efficiently. Automapper makes our lives easy with minimal steps. In a nutshell, AutoMapper is an object-object mapper. It transforms the input object of one type into an output object of another type.

Requirements
    Visual Studio 2017.
    Auto Mapper NuGet Package
    Auto Mapper Dependency Injection Package

In this example, I’ve taken two classes, Employee and EmployeeModel.
    namespace ASPNETCORE_AUTOMAPPER.Models {  
        public class Employee {  
            public int Id {  
                get;  
                set;  
            }  
            public string Name {  
                get;  
                set;  
            }  
            public string Designation {  
                get;  
                set;  
            }  
            public string City {  
                get;  
                set;  
            }  
            public string State {  
                get;  
                set;  
            }  
        }  
    }  
    namespace ASPNETCORE_AUTOMAPPER.Models {  
        public class EmployeeModel {  
            public int Id {  
                get;  
                set;  
            }  
            public string Name {  
                get;  
                set;  
            }  
            public string Designation {  
                get;  
                set;  
            }  
            public Address Address {  
                get;  
                set;  
            }  
        }  
        public class Address {  
            public string City {  
                get;  
                set;  
            }  
            public string State {  
                get;  
                set;  
            }  
        }  
    }  

We are getting Employee object from the end user and trying to assign it to EmployeeModel with each property like below, which is a tedious job and in real time scenarios, we may have plenty of properties as well as complex types. So this is an actual problem.
    [HttpPost]  
    public EmployeeModel Post([FromBody] Employee employee) {  
        EmployeeModel empmodel = new EmployeeModel();  
        empmodel.Id = employee.Id;  
        empmodel.Name = employee.Name;  
        empmodel.Designation = employee.Designation;  
        empmodel.Address = new Address() {  
            City = employee.City, State = employee.State  
        };  
        return empmodel;  
    }  


To overcome this situation, we have a library called AutoMapper.
Incorporate this library into your application by following the below steps.
Open Visual Studio and Click on File - New Project and select ASP.NET CORE WEB APPLICATION,


Click on Ok and you’ll get the below window where you have to select WebApp (MVC).


As soon as you click on the Ok button your application is ready.

Now, the actual auto mapper should take place. For that, we need to add NuGet reference to the solution. Make sure we have to add two references to solution
    Add Main AutoMapper Package to the solution,

Now, add the Auto mapper dependency Injection Package,

Now, call AddAutoMapper from StartUp.cs file as shown below,
public void ConfigureServices(IServiceCollection services) {  
            services.AddMvc();  
            services.AddAutoMapper();  
        }  


Now, create the MappingProfile.cs file under the root project and write the below snippet
 public class MappingProfile: Profile {  
            public MappingProfile() {  
                CreateMap < Employee, EmployeeModel > ()  
            }  
        }  


Here CreateMap method is used to map data between Employee and EmployeeModel.

If you observe here we called ForMember method, which is used when we have different datatypes in source and destination classes.

Employee Class should be like this,
    namespace ASPNETCORE_AUTOMAPPER.Models {  
        public class Employee {  
            public int Id {  
                get;  
                set;  
            }  
            public string Name {  
                get;  
                set;  
            }  
            public string Designation {  
                get;  
                set;  
            }  
            public string City {  
                get;  
                set;  
            }  
            public string State {  
                get;  
                set;  
            }  
        }  
    }  


EmployeeModel.cs should be like this,
    namespace ASPNETCORE_AUTOMAPPER.Models {  
        public class EmployeeModel {  
            public int Id {  
                get;  
                set;  
            }  
            public string Name {  
                get;  
                set;  
            }  
            public string Designation {  
                get;  
                set;  
            }  
            public Address Address {  
                get;  
                set;  
            }  
        }  
        public class Address {  
            public string City {  
                get;  
                set;  
            }  
            public string State {  
                get;  
                set;  
            }  
        }  
    }
 

In Employee.cs file having City and State properties but in EmployeeModel.cs we have Address type. So if we try to map these two models we may end up missing type configuration error. So to overcome that issue we have to use ForMember method which tells mapper what properties it should map for that particular Address field. So we have to tweak the MappingProfile.cs file like below:
    public class MappingProfile: Profile {  
        public MappingProfile() {  
            CreateMap < Employee, EmployeeModel > ().ForMember(dest => dest.Address, opts => opts.MapFrom(src => new Address {  
                City = src.City, State = src.State  
            }));  
        }  
    }  

So the next step is we have to hook this up from our controller;  just follow the below snippet
    namespace ASPNETCORE_AUTOMAPPER.Controllers {  
        public class EmployeeController: Controller {  
            private readonly IMapper _mapper;  
            public EmployeeController(IMapper mapper) {  
                _mapper = mapper;  
            }  
            public IActionResult Index() {  
                    return View();  
                }  
                [HttpPost]  
            public EmployeeModel Post([FromBody] Employee employee) {  
                EmployeeModel empmodel = new EmployeeModel();  
                empmodel = _mapper.Map < Employee, EmployeeModel > (employee);  
                return empmodel;  
            }  
        }  
    }
 

Here we have injected IMapper to EmployeeController and performed mapping operation between Employee and EmployeeModel

If you pass data to Employee object,  it will directly map to EmployeeModel object with the help of Mapper.

Now if you observe, EmployeeModel is filled in with all the property data with the help of Mapper. This is the actual beauty of AutoMapper.

So if you come across a requirement to map data from your DTOs to Domain object choose Automapper and it will do all your work with less code.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: URL Creation Fundamentals In MVC

clock November 8, 2021 06:49 by author Peter

In this article, we are going to explore different ways of URL creation in MVC and different fundamental concepts of MVC. So let's get started with MVC fundamentals. We have two different approaches available while creating an URL in MVC framework.
    ActionLink
    Raw HTML

Action LInk in the background queries the routing engine whenever the URL associated with the given controllers ACTION. Sometimes we do have Custom URLs associated with an action, and we require to change that URL in future. For this scenario actionLink will pick up the latest URL, you don't need to make any changes.

On the other hand, if you are using raw HTML, you need to update your links when URLs changed.

As a good programmer, we should always avoid changing URLs as URLs are the public contract of your app and can be referenced by other apps, and many times users bookmark the URLs. If you change them, all these bookmarks and references will be broken.

In the end, the decision is up to the programmer's choice, no hard and fast rule here.

Again, the simplest way is using raw HTML

1: Raw HTML
Example,
<a href = "Courses/Index"> View Course</a>

2: ActionLink
Below is the example of using ActionLink for URL creation.
@HTML.ActionLink("View Courses","Index","Courses")

If the targeted action needs a parameter we can make use of an anonymous object to pass the parameter values.
@HTML.ActionLink("View Courses","Index","Courses", new {id = 1})

This will generate a link as - courses/index/1

This method doesn't generate the link for a reason, we need to pass another argument to ActionLink. This argument can be null or an anonymous object to render any additional HTML attribute.
@HTML.ActionLink("View Courses","Index","Courses", new {id = 1}, null)

We have different HTML helpers available in MVC 

Type Helper Method
ViewResult View()
PartialViewResult PartialView()
RedirectResult Redirect()
ContentResult Content()
JsonResult Json()
RedirectToRouteResult RedirectToAction()
FileResult File()
HttpNotFoundResult HttpNotFound()
EmptyResult  

Passing Data to views in MVC
We should avoid passing data using ViewData and ViewBag as these methods are fragile and need a lot of casting which makes code ugly. Instead, we can pass model or viewModel directly to view.
return View(Course);

Razor Views
@if(condition)
{
    // c# or HTML code
}


@foreach(...)
{
}


We can render a class or any attribute conditionally as follows,
@{
    var className=Model.Movies.Count >3 ? "Popular" : null;
}
<h2 class = "@className">...</h2>

Partial View

@Html.Partial("_NavBar")

Types of Routing in MVC
1: Convention based Routing

Here we can specify the routing in RouteConfig.cs file and mention the Controller, action which needs to be invoked using mapRoute method of routes collection.

2: Attribute based Routing

Here we can apply route by decorating the action method with the Route keyword followed by the path.

Authentication in MVC
Use [authorize] keyword. Apply it to action, controller or globally (in FilterConfig.cs)
Enabling Social Login in MVC

Step 1
Enable SSL: Select project, press F4, set SSL enabled to true.

Step 2
Copy SSL URL, select the project, go to properties, in the Web tab, set startup URL.

Step 3
Apply RequireSSL filter globally in FilterConfig.cs file.

Step 4
Register your app with external authentication providers to get secret key/secret. In AppStart.cs/Startup.Auth.cs, add corresponding providers and your key/secret.
Summary

In this article, we explored different ways of URL creation in MVC and different fundamental concepts of MVC. I hope you liked the article. Until Next Time - Happy Learning Cheers



ASP.NET MVC Hosting - HostForLIFEASP.NET :: State Management In ASP.NET MVC

clock October 29, 2021 09:15 by author Peter

As we all know, HTTP is a stateless protocol, i.e., each HTTP request does not know about the previous request. If you are redirecting from one page to another page, then you have to maintain or persist your data so that you can access it further. To do this, there were many techniques available in ASP.NET like ViewState, SessionState,

ApplicationState etc.
ASP.NET MVC also provides state management techniques that can help us to maintain the data when redirecting from one page to other page or in the same page after reloading. There are several ways to do this in ASP.NET MVC -
    Hidden Field
    Cookies
    Query String
    ViewData
    ViewBag
    TempData

The above objects help us to persist our data on the same page or when moving from “Controller” to “View” or “Controller” to Controller”. Let us start practical implementation of these so that we can understand in a better way.

Hidden Field
It is not new, we all know it from HTML programming. Hidden field is used to hide your data on client side. It is not directly visible to the user on UI but we can see the value in the page source. So, this is not recommended if you want to store a sensitive data. It’s only used to store a small amount of data which is frequently changed.

The following code is storing the Id of employee and its value is 1001.
    @Html.HiddenFor(x=>x.Id)  

If you open the page source code for that page in the browser, you will find the following line of code, which is nothing but the HTML version of the above code with value. Just focus on last three attributes.

    <input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Id" name="Id" type="hidden" value="1001" />  

Cookies
Cookies are used for storing the data but that data should be small. It is like a small text file where we can store our data. The good thing is that a cookie is created on client side memory in the browser. Most of the times, we use a cookie for storing the user information after login with some expiry time. Basically, a cookie is created by the server and sent to the browser in response. The browser saves it in client-side memory.

We can also use cookies in ASP.NET MVC for maintaining the data on request and respond. It can be like the below code.
    HttpCookie cookie = new HttpCookie("TestCookie");  
    cookie.Value = "This is test cookie";  
    this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);  


Here, we have created one cookie and named it as “TestCookie”. We can create multiple cookies and add with Response. For getting the value from an existing cookie, we first need to check that the cookie is available or not; then, we can access the value of the cookie.
    if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("TestCookie"))  
    {  
        HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["TestCookie"];  
      
        ViewBag.CookieMessage = cookie.Value;  
    }  

Cookies are all depended on expiry, you can create a cookie on one action method in a controller and it will save on the client side and can be accessed in another action method easily.

Query String
In ASP.NET, we generally use a query string to pass the value from one page to the next page. Same we can do in ASP.NET MVC as well.
http://localhost:49985/home/editemployee?name=TestValue

I am making one request with the above URL. You can see that in this, I am passing name’s value as a query string and that will be accessible on “EditEmployee” action method in “Home” controller as the following image shows.

ViewData
It helps us to maintain your data when sending the data from Controller to View. It is a dictionary object and derived from ViewDataDictionary. As it is a dictionary object, it takes the data in a key-value pair.

Once you create ViewData object, pass the value, and make redirection; the value will become null. The data of ViewData is not valid for next subsequent request. Take care of two things when using ViewData, first, check for null and second, check for typecasting for complex data types.
    public ActionResult Index()  
    {  
        Employee emp = new Employee()  
        {  
            Id = 1001,  
            Name = "Peter",  
            Address = "London",  
            Age = 25  
        };  
                  
        ViewData["Message"] = "This is ViewData";  
        ViewData["Emp"] = emp;  
      
        return View();  
    }  


The above code contains two ViewData dictionary objects - ViewData["Message"] and ViewData["Emp"]. The first one is a simple string value but the next one contains complex employee data. When the View is going to render, we need to first check the ViewData for null and if it is not, then we can get the value.
    @{  
        ViewBag.Title = "Home Page";  
    }  
      
    <div class="row">  
        <div class="col-md-4">  
            <h2>Employee Details</h2>  
            <br />  
            <p>  
                @if(ViewData["Message"] !=null)  
                {  
                    <b>@ViewData["Message"].ToString();</b>  
                }  
            </p>  
            <br />  
            @if (ViewData["Emp"] != null)  
            {  
      
                var emp = (MVCStateManagement.Models.Employee)ViewData["Emp"];  
                <table>  
                    <tr>  
                        <td>  
                            Name :  
                        </td>  
                        <td>  
                            @emp.Name  
                        </td>  
                    </tr>  
                    <tr>  
                        <td>  
                            Address :  
                        </td>  
                        <td>  
                            @emp.Address  
                        </td>  
                    </tr>  
                    <tr>  
                        <td>  
                            Age :  
                        </td>  
                        <td>  
                            @emp.Age  
                        </td>  
                    </tr>  
                </table>              
            }  
        </div>  
    </div>  

Note
    If you are using ViewData that is not defined on Controller, then it will throw an error; but with ViewBag, it will not.
    Do not use ViewBag and ViewData with the same name, otherwise, only one message will display. See the following code in the controller is using both ViewData and ViewBag with same name “Message”.
    public ActionResult Index()  
    {  
        ViewData["Message"] = "This is ViewData";  
        ViewBag.Message = "This is ViewBag";              
      
        return View();  
    }  

On view defined both as following.  
    <b>@ViewBag.Message</b>    
    @if(ViewData["Message"]!=null)    
    {    
        ViewData["Message"].ToString();    
    }  


The output will show only one message and that will be the last one [in this case, message will be “This is ViewBag”].

TempData
TempData is also a dictionary object as ViewData and stores value in key/value pair. It is derived from TempDataDictionary. It is mainly used to transfer the data from one request to another request or we can say subsequent request. If the data for TempData has been read, then it will get cleaned. To persist the data, there are different ways. It all depends on how you read the data.

No Read Data
If you haven’t read the data in redirection process, then your data is available with the next subsequent request. You can see that in the following code, we have set up a TempData[“Emp” but neither read it in any action method nor in view.

So, once the “About” page renders and if we move to “Contact” page, the TempData[“Emp”] will be available.

Note
Do not read data on View.
    public ActionResult Index()  
    {  
        Employee emp = new Employee() { Id = 1001, Name = "Peter", Address = "London", Age = 25 };  
      
        //Setting the TempData  
        TempData["Emp"] = emp;  
        return RedirectToAction("Index1");  
    }  
    public ActionResult Index1()  
    {  
        //Not reading TempData  
        return RedirectToAction("Index2");  
    }  
    public ActionResult Index2()  
    {  
        //Not reading TempData  
        return RedirectToAction("About");  
    }  
    public ActionResult About()  
    {  
        //Not reading TempData  
        return View();  
    }    
           
    public ActionResult Contact()  
    {  
        //Data will available here because we have not read data yet  
        var tempEmpData = TempData["Emp"];  
        return View();  
     }  


Normal Data Read
If you read the data on “About” page when it will render and try to access the value on “Contact” page, it will not be available.
    @{  
        ViewBag.Title = "About";  
    }  
    <h2>About Page</h2>  
    <br />  
    @{   
        var data = (MVCStateManagement.Models.Employee)TempData["Emp"];  
    }  

TempData will not be available with Contact page because we have already read that data on “About” page. TempData is only available with subsequent request if you have not read yet.
    public ActionResult Contact()  
    {  
        //Data will not available here because already read on About page  
        var tempEmpData = TempData["Emp"];  
        return View();  
     }  


Keep TempData
If you still want to persist your data with the next request after reading it on “About” page that you can use “Keep()” method after reading data on “About” page. The Keep method will persist your data for next subsequent request.
    @{   
        var data = (MVCStateManagement.Models.Employee)TempData["Emp"];  
        TempData.Keep();  
    }  
    public ActionResult Contact()  
    {  
        //TempData will available here because we have keep on about page  
        var tempEmpData = TempData["Emp"];  
        return View();  
     }  


Peek TempData
Using Peek() method, we can directly access the TempData value and keep it for next subsequent request.
    @{   
        var data = (MVCStateManagement.Models.Employee)TempData.Peek("Emp");      
    }  

When we move to “Contact” page, the TempData will be available.
    public ActionResult Contact()  
    {  
        //TempData will available because we have already keep data using Peek() method.  
        var tempEmpData = TempData["Emp"];  
        return View();  
     }  


I hope this post helps you. Please share your feedback which will help me improve the next posts. If you have any doubts, please ask in the comments section.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in