Deserializing JSON object to runtime type or dynamic types using JsonConvert.DeserializeObject and reflection


JsonConvert.DeserializeObject method has 8 overloaded methods one of them will full fill our requirement.

If we want to deserialize Json object to a runtime type or dynamic type we can use 3rd overload method of JsonConvert.DeserializeObject

these are the 8 overloaded methods of JsonConvert.DeserializeObject

 

Screenshot_10

Screenshot_13

Screenshot_14

Screenshot_15

Screenshot_16

Screenshot_17

Screenshot_18

Screenshot_19

If we want to deserialize Json object to a runtime type or dynamic type we can use 3rd overload method of JsonConvert.DeserializeObject

string jsonData = "{\"key\":\"value\"}";
string typeName = "SampleNamespace.SampleClassName";
Type requestType = Type.GetType(typeName);
var result = JsonConvert.DeserializeObject(jsonData, requestType);

In the above code typeName is class name which is matching json properties.

then create the type using Type.GetType() method.

then pass this type to our JsonConvert.DeserializeObject method.

Happy Coding SmileComputer

Advertisements

How can we force clients to refresh JavaScript files?


Q: How can we force web clients to refresh or load latest version javascript files from the web server.

This is the problem most of the web developers facing after deploying their newer versions of javascript files.

We normally ask the customer to hit Ctrl + F5 to ensure that all the latest javascript files loaded from server not from the cache.

But we can solve this in different ways as follows

Solution 1: If you are maintaining javascript versioning

If you are using javascript versions, it’s easy to solve the issue. i.e we just need to add the version to javascript file path as follows

<script src="~/scripts/demojs.js?100"></script>
<script src="~/scripts/demojs.js?version=100"></script>

so If the version of the file changed then the url also change. so if the url is different than the file which is already in cache, the browser (client) will request to get latest file from the server.

So these file will render to clients as follows

Loading from cache

image

Loading from server

image

Solution 2: If you are not using versioning use Asp.Net MVC datetime object ticks

In this case we just use ticks from C# datetime object as follows

<script src="~/scripts/demojs.js?@DateTime.Now.Ticks"></script>
<script src="~/scripts/demojs.js?currentTime=@DateTime.Now.Ticks"></script>

image

Solution 3: Restart application and Recycle Application pool in IIS

Please do following steps after completion of your deployment in IIS

  1. Restart your website

image

2. Then find the applicationpool of your website and recycle it.

image

In case of Microsoft Azure websites

Screenshot_10

Thanks

Happy coding ComputerSmile

How to implement cascading dropdownlist in asp.net mvc using angularJS


 

Here we will learn how to implement cascading dropdown list using angularjs and asp.net mvc.

Should have knowledge on:

You should have knowledge on html , javascript , angularJS and C#.net and asp.net MVC

Preparation:

1. In this article we will use asp.net mvc as service provider and angularJS as client side framework.

2. In asp.net mvc we will build 3 services to get Company Locations, Departments and Managers data.

3. We will use AngularJS $http service to get data from these services.

4. We will use scope object to bind data to UI

Execution:

Open visual Studio and select new project from file menu

and select Asp.Net web application template and enter name then click on OK button.

image

Click on empty tile and select MVC checkbox to create Asp.net MVC empty project then click on OK button

image

Add Content folder and bootstrap.min.css file in it, as shown in below screenshot

Add Scripts folder and angular.min.js file in it, as shown in below screenshot

image

Add app.js file in Scripts folder and write the following code in it.

var MyModule = angular.module('MyModule', []);

 

above code creates angularjs module.

image

Next Create angular Controller for this module as follows

MyModule.controller('myController', ['$scope', '$http', function (scope, http) {
    //Get Locations
    scope.getLocations = function () {
        //Get Locations service call
        http({
            method: 'Get',
            url: '/Home/GetCompanyLocations'
        }).success(function (data, status, headers, config) {
            //assign locations data to scope
            scope.locations = data;
            //setting default value
            if (scope.locations.length > 0) {
                scope.selectedLocation = scope.locations[0];
            }
        }).error(function (data, status, headers, config) {
            alert("Error occured");
        });
    };
    //Get Departments   
    scope.getDepartments = function () {
        if (scope.selectedLocation.Id > 0) {
            scope.departments = null;
            scope.managers = null;
            //Get Departments service call
            http({
                method: 'POST',
                url: '/Home/GetDepartments',
                data: { locationId: scope.selectedLocation.Id }
            }).success(function (data, status, headers, config) {
                //assign departments data to scope
                scope.departments = data;
                //setting default value
                if (scope.departments.length > 0) {
                    scope.selectedDepartment = scope.departments[0];
                }
            }).error(function (data, status, headers, config) {
                alert("Error occured");
            });
        }
        else {
            scope.departments = null;
            scope.managers = null;
        }
    };
    //Get Managers
    scope.getManagers = function () {
        if (scope.selectedDepartment.Id > 0) {
            //Get Managers service call
            http({
                method: 'POST',
                url: '/Home/GetManagers',
                data: { deptId: scope.selectedDepartment.Id }
            }).success(function (data, status, headers, config) {
                //assign managers data to scope
                scope.managers = data;
                //setting default value
                if (scope.managers.length > 0) {
                    scope.selectedManager = scope.managers[0];
                }
            }).error(function (data, status, headers, config) {
                alert("Error occured");
            });
        }
        else {
            scope.managers = null;
        }
    };
}]);

 

Explanation:

In the above code we have 3 service calls for three dropdowns

1. getLocations

This service get called when the page loads, we can use ngInit directive to call some method on load.

In this service call we will get all the company locations and in success call back, we are assigning the locations to scope.locations object and setting default value for the dropdown using selectedLocation model

2. getDepartments

This service get called when the locations dropdown selection changed, we can use ngChnage directive to call some method on change.

In this service call we will get all the location departments and in success call back, we are assigning the departments to scope.departments object and setting default value for the dropdown using selectedDepartment model

2. getManagers

This service get called when the departments dropdown selection changed, we can use ngChnage directive to call some method on change.

In this service call we will get all the department managers and in success call back, we are assigning the managers to scope.managers object and setting default value for the dropdown using selectedManager model

Add Home controller to controllers folder and one model to models folder and add one action method in home controller and generate a view for it.

image

Write models code in Model (CompanyLocation.cs)

namespace CascadingDropdownList.Models
{
    public class CompanyLocation
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int LocationId { get; set; }
    }
    public class Manager
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int DepartmentId { get; set; }
    }
}

 

Write 3 services 1. GetCompanyLocations 2. GetDepartments 3. GetManagers as follows

        public JsonResult GetCompanyLocations()
        {
            var locations = new List<CompanyLocation>() {
                new CompanyLocation() { Id=0,Name="–select–"},
                new CompanyLocation() { Id=1,Name="Hyderabad"},
                new CompanyLocation() { Id=2,Name="Chennai"},
                new CompanyLocation() { Id=3,Name="Delhi"},
                new CompanyLocation() { Id=4,Name="Bangalore"}
            };
            return Json(locations, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult GetDepartments(int locationId)
        {
            var departments = new List<Department>() {
                new Department() { Id=1,Name="Accounts",LocationId=1},
                new Department() { Id=2,Name="Software",LocationId=1},
                new Department() { Id=3,Name="CustomerCare",LocationId=1},
                new Department() { Id=4,Name="IT",LocationId=1},
                new Department() { Id=5,Name="Software",LocationId=2},
                new Department() { Id=6,Name="CustomerCare",LocationId=2},
                new Department() { Id=7,Name="IT",LocationId=2},
                new Department() { Id=8,Name="Accounts",LocationId=3},
                new Department() { Id=9,Name="CustomerCare",LocationId=3},
                new Department() { Id=10,Name="IT",LocationId=4}
            };
            var result = departments.Where(d => d.LocationId == locationId).ToList();
            result.Insert(0, new Department() { Id = 0, Name = "–select–" });
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult GetManagers(int deptId)
        {
            var locations = new List<Manager>() {
                new Manager() { Id=1,Name="Venki",DepartmentId=1},
                new Manager() { Id=2,Name="Sri",DepartmentId=5},
                new Manager() { Id=3,Name="Balu",DepartmentId=6},
                new Manager() { Id=4,Name="Gopi",DepartmentId=10},
                new Manager() { Id=5,Name="Ramesh",DepartmentId=3},
                new Manager() { Id=6,Name="Ganesh",DepartmentId=2},
                new Manager() { Id=7,Name="Shiva",DepartmentId=7},
                new Manager() { Id=8,Name="Naidu",DepartmentId=2},
                new Manager() { Id=9,Name="ThataRao",DepartmentId=3},
                new Manager() { Id=10,Name="Bala",DepartmentId=4},
                new Manager() { Id=11,Name="Chandu",DepartmentId=8},
                new Manager() { Id=12,Name="Chaitanya",DepartmentId=9}
            };
            var result = locations.Where(d => d.DepartmentId == deptId).ToList();
            result.Insert(0, new Manager() { Id = 0, Name = "–select–" });
            return Json(result, JsonRequestBehavior.AllowGet);
        }

 

Then write following code in View(Index.cshtml)

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/app.js"></script>
<div ng-app="MyModule">
    @* using ng-init getLocations() method invoked when the div loads*@
    <div ng-controller="myController" ng-init="getLocations()">
        <div class="row">
            <div class="form-group col-md-offset-2 col-md-2">
                <label for="loc">Select Location:</label>
                <select ng-model="selectedLocation" ng-change="getDepartments()" class="form-control" id="loc"
                        ng-options="location.Name for location in locations track by location.Id"></select>
                <br />
                <label for="dept" ng-show="departments">Select Department:</label>
                <select ng-model="selectedDepartment" ng-change="getManagers()" ng-show="departments" class="form-control" id="dept"
                        ng-options="department.Name for department in departments track by department.Id"></select>
                <br />
                <label for="mng" ng-show="managers">Select Manager:</label>
                <select ng-model="selectedManager" ng-show="managers" class="form-control" id="mng"
                        ng-options="manager.Name for manager in managers track by manager.Id"></select>
                <br />
            </div>
        </div>
    </div>
</div>

Output:

image

image

image

image

Happy Coding ComputerSmile

Screenshot_18

Partial Views in MVC 5 with model binding


Q: What is partial view?

Ans: A partial view is a customized shared view, which can’t be served directly and can be used in other views. i.e Reusable custom view.

Q: What are the advantages with partial views?

Ans: 1. Sometimes you need to return just a piece and you can do it by a async request (using ajax). In these cases, you use an action that returns a Partial View.

2. Sometimes you need to implement an View that need to add a piece of code, so, you can render it using a Partial View.

3. Using partial views you can avoid code redundancy, i.e partial view are reusable

Q: How to Implement partial view in MVC

Ans: Here we will learn how to implement partial view in mvc with product catalog example.

let’s create product catalog data first

To reate product catalog data first create model as follows

Product Model
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; }
    public string ImagePath { get; set; }
}

Now create product catalog data

Products
public class Products
    {
        public List<Product> GetProducts()
        {
            return new List<Product>()
            {
                new Product{ Id=1,Name="F&D E200 (2.0 Channel)",Price=849,Description="F&D's E200 is an ergonomically designed sound bar which can conveniently get attached to your laptop or PC. You may place it in your purse and carry it to work without any excess weight or bulk.",ImagePath="/Content/Images/1.jpeg"},
                new Product{ Id=2,Name="F&D F203G Laptop Speakers (2.1 Channel)",Price=1289,Description="2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis",ImagePath="/Content/Images/2.jpeg"},
                //new Product{ Id=3,Name="Zebronics ZEB-S310 Club Wired Laptop Speakers (Black, 2…",Price=199,Description="Interface : usb, power input : (dc) 5v, frequency response : 20hz~20khz, driver unit : 2.5 x 2, output power : 3w x 2 (rms), s/n ratio : ?75 db, separation : ?65 db, impedance : 4 ?, dimensions : 70 x 70 x 187mm (wxhxd), input connectivity : 3.5 mm jack.",ImagePath="/Content/Images/3.jpeg"},
                new Product{ Id=4,Name="Portronics Pure Sound Portable Speaker (2.0 Channel)",Price=1165,Description="8 hrs Battery Life,Satellites",ImagePath="/Content/Images/4.jpeg"},
                new Product{ Id=5,Name="Philips DSP 2800 Home Audio (5.1 Channel)",Price=2980,Description="2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis",ImagePath="/Content/Images/5.jpeg"},
                //new Product{ Id=6,Name="Intex IT-880 s Wired Laptop Speakers (Black, 2.1 Channel)",Price=675,Description="2.1 Channel Stereo,Subwoofer,Speaker,Headphone Socket",ImagePath="/Content/Images/6.jpeg"},
                new Product{ Id=7,Name="JBL Charge Speaker (Single Unit Channel)",Price=6749,Description="20 W RMS Output Power,5.1 Home Audio,inch Woofer,inch Full Range,High Gloss Finish",ImagePath="/Content/Images/7.jpeg"},
                new Product{ Id=8,Name="Intex IT-880 S OS Wired Laptop Speakers (Black, 2.1 Cha…",Price=649,Description="150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device",ImagePath="/Content/Images/8.jpeg"},
                new Product{ Id=9,Name="Quantum QHM611 Wired Laptop Speakers (Black, 2.0 Channel)",Price=125,Description="150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device",ImagePath="/Content/Images/9.jpeg"},
                new Product{ Id=10,Name="Lenovo Portable Speaker M0520 (2.0 Channel)",Price=812,Description="150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device",ImagePath="/Content/Images/10.jpeg"}
            };
        }
    }

Now create one action method in controller as follows

Action Method
//
// GET: /PartialViews/
public ActionResult Index()
{
    Products products = new Products();
    return View(products.GetProducts());
}

 

Now add a view for the above action as follows

Right click on the action method and choose addview…

image

image

Click add to create view.

Write the following code in the created view

Product Catalog view
@model IEnumerable<MVCControls.Models.Product>
@{
    ViewBag.Title = "Partial views in MVC 5 || Chikkanti.wordpress.com";
    Layout = null;
}

<div style="padding: 5px;width:850px;margin:0px auto;">
    <h2>Partial views in MVC 5</h2>
    @foreach (var product in Model)
    {
        @Html.Partial("_ProductBox", product)
    }
</div>

 

In the above code @html.Partial is a helper class and we can use this to render our partial view. For this helper we are passing two parameters

1.”_ProductBox”: partial view name

2.product : Model for the partial view

Now let’s add the partial view in shared folder under views as follows

RightClick on Shared folder under views and choose add then view and fill the following details

image

image

After adding this partial view write the following code into it.

Partial View
@model MVCControls.Models.Product
<div class="products">
    <div>
        @Html.HiddenFor(m => m.Id)
    </div>
    <div>
        <img src="@Model.ImagePath" alt="@Model.Name" />
    </div>
    <div style="font-weight:bold;">
        @Html.LabelFor(m => m.Name):@Html.DisplayFor(m => m.Name)
    </div>
    <div style="color:green;">
        @Html.LabelFor(m => m.Price):RS.@Html.DisplayFor(m => m.Price)
    </div>
    <div style="color:brown;">
        @Html.LabelFor(m => m.Description):@Html.DisplayFor(m => m.Description)
    </div>
</div>
<style>
    .products {
        width: 150px;
        height: 200px;
        border: 1px #ffd926 solid;
        padding: 15px;
        float: left;
        overflow: hidden;
        overflow-wrap: break-word;
        overflow-y: hidden;
    }
</style>

 

Now Rebuild the application and run

image

Multi fileupload in MVC 5 & Razor


In this post we will learn how to upload multiple files at a time using multi fileupload in MVC 5 & razor

Add one controller and write the following code in it

Action Method
//
// GET: /Multi Fileupload/
//
public ActionResult Index()
{
return View();
}
//
// POST: /Multi Fileupload/
//
[HttpPost]
public ActionResult Index(ICollection<HttpPostedFileBase> fu_files)
{
var directory = Server.MapPath(“~/Content/Uploads/”);
foreach (HttpPostedFileBase file in fu_files)
{
if (file != null && file.ContentLength > 0)
{
Stream fs = file.InputStream;
int size = file.ContentLength;
byte[] bytes = new byte[size];
fs.Read(bytes, 0, size);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
System.IO.File.WriteAllBytes(directory + file.FileName, bytes);
}
}
Dictionary<string, string> UploadedImages = new Dictionary<string, string>();
foreach (var item in Directory.EnumerateFileSystemEntries(directory))
{
string[] str = item.Split(new char[] { ‘\\’ }, StringSplitOptions.RemoveEmptyEntries);
UploadedImages.Add(str[str.Length – 1], “/Content/Uploads/” + str[str.Length – 1]);
}
ViewBag.UploadedImages = UploadedImages;
return View();
}

Then add the view and write the following code

View
@{
ViewBag.Title = “Multi Fileupload in MVC || Chikkanti.wordpress.com”;
}<h2>Multi Fileupload in MVC</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = “multipart/form-data” }))
{
<table border=”1″ style=”border-color:black;background:#f5c9c9″>
<tr>
<td>
<input type=”file” name=”fu_files” multiple />
</td>
<td>
<input type=”submit” id=”resume” name=”name” value=”Submit” />
</td>
</tr>
@if (ViewBag.UploadedImages != null)
{
<tr>
<td><strong>Name</strong></td>
<td><strong>Image</strong></td>
</tr>
Dictionary<string, string> Images = ViewBag.UploadedImages as Dictionary<string, string>;
foreach (var Image in Images.Keys)
{
<tr>
<td>@Image</td>
<td><img src=’@Images[Image] height=”100px” width=”100px” /></td>
</tr>
}
}
else
{
<tr>
<td colspan=”2″><span>No files uploaded.</span></td>
</tr>
}
</table>
}

Rebuild the application and run

image

image

image

image

Upload and display files to server in MVC 5 using fileupload in Razor.


In this we will learn how to save files to server and display in mvc 5 using fileupload in rezor view engine.

First Create a Controller action method as follows

Action Method
//
// GET: /Fileupload/
//
public ActionResult Index()
{
    return View();
}
//
// POST: /Fileupload/
//
[HttpPost]
public ActionResult Index(HttpPostedFileBase fu_file)
{
    var directory = Server.MapPath("~/Content/Uploads/");
    if (fu_file != null && fu_file.ContentLength > 0)
    {
        Stream fs = fu_file.InputStream;
        int size = fu_file.ContentLength;
        byte[] bytes = new byte[size];
        fs.Read(bytes, 0, size);
        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }
        System.IO.File.WriteAllBytes(directory + fu_file.FileName, bytes);
    }
    Dictionary<string, string> UploadedImages = new Dictionary<string, string>();
    foreach (var item in Directory.EnumerateFileSystemEntries(directory))
    {
        string[] str = item.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
        UploadedImages.Add(str[str.Length – 1], "/Content/Uploads/" + str[str.Length – 1]);
    }
    ViewBag.UploadedImages = UploadedImages;
    return View();
}

Generate or add the view for the action and write the following code

View
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <table border="1" style="border-color:black;background:#f5c9c9">
        <tr>
            <td>
                <input type="file" name="fu_file" />
            </td>
            <td>
                <input type="submit" id="resume" name="name" value="Submit" />
            </td>
        </tr>
        @if (ViewBag.UploadedImages != null)
        {
            <tr>
                <td><strong>Name</strong></td>
                <td><strong>Image</strong></td>
            </tr>
            Dictionary<string, string> Images = ViewBag.UploadedImages as Dictionary<string, string>;
            foreach (var Image in Images.Keys)
            {
                <tr>
                    <td>@Image</td>
                    <td><img src='@Images[Image]' height="100px" width="100px" /></td>
                </tr>
            }
        }
        else
        {
            <tr>
                <td colspan="2"><span>No files uploaded.</span></td>
            </tr>
        }
    </table>
}

 

Rebuild the application and run

image

image

image

image

Dropdownlist with inline selectlist in MVC 5


In this post we will learn how to implement dropdownlist with inline selectlist in MVC 5.

lets start by creating action method in controller

Action Method
public ActionResult Index2(string gender)
{
    ViewBag.gender = gender;
    return View();
}

 

add a view for this action method and write the following code

View
@{
    ViewBag.Title = "Dropdownlist with inline selectlist || Chikkanti.wordpress.com";
}

<h2>Dropdownlist with inline selectlist</h2>

@using (Html.BeginForm())
{
    @Html.Label("Gender : ")
    @Html.DropDownList("gender", new SelectList(new List<SelectListItem>() {
    new SelectListItem(){Text="Male", Value="Male"},
    new SelectListItem(){Text="Female", Value="Female"}
    }, "Value", "Text", "..Select.."))
    <input type="submit" name="name" value="Submit" />
    if (!string.IsNullOrEmpty(ViewBag.gender))
    {
        string message = "Selected Gender : " + ViewBag.gender;
        @Html.Label(message)
    }
}

 

Now Rebuild the application and run

image

image