How to Add/Remove View Engines in ASP.NET MVC

Here we will learn how to add/remove view engines in Asp.Net MVC.

Points covered:
1. Displaying the total available views
2. Clearing all the views
3. Adding the required views

Reading all the available view engines
using System.Web.Mvc;
namespace MVC.Controllers
    public class HomeController : Controller
        // GET: Home
        public string Index()
            string viewEngines = string.Empty;
            foreach (var item in ViewEngines.Engines)
                viewEngines += item + "</br>";
            return viewEngines;
Clearing all available view engines and adding required
using System.Web.Mvc;
using System.Web.Routing;
namespace MVC
    public class MvcApplication : System.Web.HttpApplication
        protected void Application_Start()
            ViewEngines.Engines.Add(new RazorViewEngine());

Happy coding..!


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










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

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


Loading from server


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>


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


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


In case of Microsoft Azure websites



Happy coding ComputerSmile TextBox post-back on each character entry

In This post I am going to Explain How to send a Request to server on every character entry in textbox control…

for this i am preparing a custom control with above functionality… named as PostBackTextBox..

First Take a Class Library Project and Delete Existing Classes then Add one class with name PostBackTextBox

Add System.Web Reference

Add System.Web Reference

and write the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
[assembly: WebResource("PostBackTextBox.Scripts.PostBackTextBox.js", "text/javascript")]
namespace PostBackTextBox
    [ToolboxData(@"<{0}:PostBackTextBox Text="""" AutoPostBack=""true"" runat=""server""></{0}:PostBackTextBox>")]
     public class PostBackTextBox : System.Web.UI.WebControls.TextBox
            public override string Text
                    return base.Text;
                    base.Text = value;

                    Attributes["value"] = value;
            public override bool AutoPostBack
                    return true;
                    base.AutoPostBack = true;
            protected override void AddAttributesToRender(HtmlTextWriter writer)
                writer.AddAttribute("onkeyup", "Refresh(;");
                writer.AddAttribute("onfocus", "SetCursorToTextEnd(;");

            protected override void OnPreRender(EventArgs e)
                Attributes["value"] = Text;
                ClientScriptManager cs = this.Page.ClientScript;
                cs.RegisterClientScriptInclude("PBTBScript", cs.GetWebResourceUrl(this.GetType(), "PostBackTextBox.Scripts.PostBackTextBox.js"));

and add one Folder with name Scripts and add one script file and set the script file properties as Build action is Embedded Resource

GoTo Script File Properties

Select Build Action As Embedded Resource

and add following code in script file

function Refresh(textControlID1) {
    __doPostBack(textControlID1, '');
function SetCursorToTextEnd(textControlID) {
    var text = document.getElementById(textControlID);
    if (text != null && text.value.length > 0) {
        if (text.createTextRange) {
            var range = text.createTextRange();
            range.moveStart('character', text.value.length);
        else if (text.setSelectionRange) {
            var textLength = text.value.length;
            text.setSelectionRange(textLength, textLength);


How to create DataTable and add primary key to DataTable in

Creating DataTable:
//create inatance of datatable
DataTable dt = new DataTable();
//give datatable name to dt
dt.TableName = "MyTable";
//add columns to datatable dt
dt.Columns.Add("ImgPath", typeof(string));
//creating primary key column
DataColumn[] Key = new DataColumn[1];
DataColumn col = new DataColumn();
//setting datatype to column
col.DataType = System.Type.GetType("System.String");
//giving column name
col.ColumnName = "Name";
//adding column to datatable dt
Key[0] = col;
// adding other columns to datatable directly
dt.Columns.Add("Desc", typeof(string));
dt.Columns.Add("Price", typeof(string));
//setting primary key to datatable
dt.PrimaryKey = Key;


Adding Data to Created DataTable:

//creating new data row
DataRow dr = dt.NewRow();
//adding data to the above created datarow
dr[0] = "ImgPath";
dr[1] = "Name";
dr[2] = "Desc";
dr[3] = "123.45";
//adding datarow to datatable

How to apply distinct Method on particular column in LINQ

Sometimes we need to select two or more columns based on one column distinct
in this situation if we have one primary column and one columns allows duplicates so now we want to read these two columns based on column which allow duplicates… in this situation if we apply Distinct method it will takes records based on primary key column, it won’t read based on other column…
To do that….follows these steps…

first create one method for DistinctBy

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
            var set = new HashSet<TKey>();
            return source.Where(element => set.Add(selector(element)));

and use this method to do Distinct based on Particular column…

var x = (from n in context.tblEmployees.Where(i => i.EMPLOYEE_ID == EmployeeId) select n).DistinctBy(i => i.EmployeeName).ToList();



How to get controls values like textboxes, checkbox, radiobuttons and dropdownlist back to controller from Razor view in mvc3

Code in Razor view:
    ViewBag.Title = "Home Page";

<img src="@Url.Content("~/Content/picture1.jpg")" />

Enter UserName:
<br />
<br />
Specifie the Timings:
@Html.RadioButton("Timinings","Morning",true) Morning
@Html.RadioButton("Timinings","Anytime",false) AnyTime
<br />
<br />
Courses List;
<br />
Receive Mails:
<input type="submit" id="btnsubmit" value="Submit" />
Code in Controller:
public class HomeController : Controller
        public ActionResult Index()
            ViewBag.Message = "Welcome to the Training Courses...";
            List<string> objcourses = new List<string>();
            ViewBag.Courses = new SelectList(objcourses);
            return View();

        public ActionResult Result(string stname, string Timinings, string Courses, bool chk)
            ViewBag.stname = stname;
            ViewBag.Timinings = Timinings;
            ViewBag.Courses = Courses;
            if(chk == true)
            ViewBag.chk = "EmailSubscribed";
                ViewBag.chk = "EmailNotSubscribed";
            return View();