All posts by Thiyagu

Removing unused View Engines in MVC

In this post, we will discuss how to remove View Engines which is not being used by the application.

Why need to remove?

If we remove View Engines which is not being used by application, then it lead to improve the performance in our application.

Discussion:

  •  As default, ASP .NET MVC will search for the webform (.aspx) view engine first  to find the match  naming conventions. After that it start to search for the views that match the Razor view engine naming conventions.

Example : 1

Here i am creating a new controller with default action, but i don’t add view for this action method.

public class SampleController : Controller
{
public ActionResult Index()
{
return View();
}

}

In this situation i am try to run the application to access the sample controller, then it will show output as shown below

Removing View Engines in MVC 4

Example : 2

Let we  removing  the view engines and register only Razor view engine like below

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();
}

Explanation:

  • It can control by placing it in Global.asax file.
  • All Engine will be clear by using ViewEngines.Engines.Clear().
  • ViewEngines.Engines.Add(new RazorViewEngine()) it will again register razor view engine to the application

Output :

 

Implemening CKEditor in MVC 4 Razor application.

How to implement CKEditor in MVC 4 Razor application.

At present may editors are available in market. Here let we discuss about how to implement  simple CKEditor in mvc application

Step : 1

Create simple MVC Razor project

Step :2

Go to http://ckeditor.com/download link and download latest version and place in the project

Step : 3

Then make reference of ckeditor.js in the folder to view as show below

@{
ViewBag.Title = “Index”;
}
<script src=”~/ckeditor/ckeditor.js”></script>
<h2>Index</h2>
<div>@Html.TextArea(“editor”, new {@class = “ckeditor”, @id = “sampleEditor”})</div>

Step 4 :

Run the application

Note :

I have to added class “ckeditor” to  textarea . If we delete ,then it will shows as simple textbox not like editor

How to use multiple model in view

If we have two model classes like Customer details and Employee detail. ASP.NET MVC allows you to pass only One model to a view. The view can be bound with one and only one model. From the above statement, we understood that either pass customer or employee details to the view. Then What if a view requires to display both models?. Let us we discuss the situation as follows:

How to overcome?

In MVC we cannot pass more than one models from a controller to the single view. To overcome this we can use ExpandoObject class.

What is ExpandoObject ?

The .NET 4.0 framework actually includes an ExpandoObject class which provides a dynamic object that allows us to add properties and methods on the fly.

  • ExpandoObject is a sealed type so we can’t use it as a base class
  • It doesn’t serialize to XML or DataContractSerializer/DataContractJsonSerializer

From msdn, Represents an object whose members can be dynamically added and removed at run time.

When to use ?

In some time we need to display more than one type of model data in to the single view. For example i am having two models namely CustomerDetails and EmployeeDetails and if i need to display both information in single view then we can use the ExpandoObject.

Example :

Model :

Creating simple model namelu CustomerDetail.cs and EmployeeDetail.cs as shown below.

CustomerDetail.cs

public class CustomerDetail
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string CustomerAdress { get; set; }
}

EmployeeDetail.cs

public class EmployeeDetail
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string EmployeeAdress { get; set; }
}

Controller :

public ActionResult Index()
{
dynamic detailModel = new ExpandoObject();
detailModel.EmployeeDetail = GetEmployeeDetail();
detailModel.CustomerDetail = GetcutomerDetail();
return View(detailModel);
}
private List<EmployeeDetail> GetEmployeeDetail()
{
List<EmployeeDetail> employeeDetail = new List<EmployeeDetail>();
employeeDetail.Add(new EmployeeDetail { EmployeeId = 1001, EmployeeName = "Aadharsh", EmployeeAdress = "xxxxxx" });
employeeDetail.Add(new EmployeeDetail { EmployeeId = 1002, EmployeeName = "GK", EmployeeAdress = "xxxxxx" });
return employeeDetail;
}
public List<CustomerDetail> GetcutomerDetail()
{
List<CustomerDetail> cutomerDetail = new List<CustomerDetail>();
cutomerDetail.Add(new CustomerDetail { CustomerId = 256, CustomerName = "Kavitha", CustomerAdress = "xxxxxx" });
cutomerDetail.Add(new CustomerDetail { CustomerId = 257, CustomerName = "Gnanam", CustomerAdress = "xxxxxx" });
return cutomerDetail;
}

View :

@using Multiple_Models_in_Single_View.Models;
@model dynamic
@{
ViewBag.Title = "Detail Page";
}
<div>============================</div>

<table>
<tr>
<th>Emp Id</th>
<th>Emp Name</th>
<th>Emp Adress</th>
</tr>
@foreach (EmployeeDetail employeeDetail in Model.EmployeeDetail)
{
<tr>
<td>@employeeDetail.EmployeeId</td>
<td>@employeeDetail.EmployeeName</td>
<td>@employeeDetail.EmployeeAdress</td>
</tr>
}
</table>
<div>============================</div>
<table>
<tr>
<th>Cus Id</th>
<th>Cus Name</th>
<th>Cus Adress</th>
</tr>
@foreach (CustomerDetail cutomerDetail in Model.CustomerDetail)
{
<tr>
<td>@cutomerDetail.CustomerId</td>
<td>@cutomerDetail.CustomerName</td>
<td>@cutomerDetail.CustomerAdress</td>
</tr>
}
</table>

OUTPUT

How to map multiple urls to the same controller/Action

In this post we are going to discuss about how to map multiple URLs to the same controller/Action by the custom route.

Below example shows how write custom route

Custom code must be place inside the RouteConfig.cs.

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute( "MultipleUrls", "{phaseone,phasetwo}", new { controller = "home", action = "index", id = "" } );

routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}",defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
}
}

Explanation :

  •  MultipleUrls : Descripe the name of the route
  •  {phaseone,phasetwo} : controllers name with comma separator
  •  new { controller = “home”, action = “index”, id = “” } : It describe, where want to redirect for the above controllers

 OUTPUT :

Thanks to my friend manjunath for rise this question and make me find this solution

 

Action Result Return Type in MVC 4

ActionResult is a return type of a controller method in ASP.NET MVC. It help us to return models to views, other return value, and also redirect to another controller’s action method. There are many derived ActionResult types in MVC that we use to return the result of a controller method to the view.

What is ActionResult ?

  •  An ActionResult is a return type of a controller method in MVC.
  •  ActionResult are more specific for a particular view
  •  It is abstract class that has many subtypes

Types of ActionResult :

  • ViewResult
  • PartialViewResult
  • ContentResult
  • RedirectResult
  • RedirectToRouteResult
  • JsonResult
  • EmptyResult
  • FileResult
  • JavaScriptResult

Let we start discussion about types of ActionResult in one by one…

ViewResult :

  • It renders a specified view to the response stream.

 Example :

public ViewResult Index() {   return View(“sampleResult”); }

PartialViewResult:

  • Renders a specifed partial view to the response stream.

Example :

public PartialViewResult SamplePartialView()
{    return PartialView(“_LoadSamplePartial”); }

Note :

  • It will load the partial view to the main view

ContentResult :

  • It display the response stream without requiring a view .(like a plain text).

Example

public ActionResult About()
{
ViewBag.Message = “Your app description page.”;
return Content(“Sample Content Action”);
}

It simply write the string value in the page

RedirectResult :

  • It is used to perform an HTTP redirect to a given URL.

Example :

public ActionResult SampleRedirectResult()
{  return Redirect(“http://www.google.com/”); }

RedirectToRouteResult :

  • RedirectToResult is used to redirect by using the specified route values dictionary.

Example :

public ActionResult SampleRedirectToRouteResult()
{
return new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new
{
controller = “Sample”,
action = “SampleRedirectToRouteResultTest”,
Id = new int?()
}));
}

JsonResult :

  • Action methods return JsonResult (JavaScript Object Notation result) that can be used in ajax based application.

Example :

public ActionResult SampleJsonResult
{
… Logic here
return Json(sampleinfo);
}

EmptyResult : 

  • It return  NULL that is EmptyResult
  • return instance of EmptyResult class

Example :

return new EmptyResult();

FileResult :

  • Return a file from an action. (Pdf,Excel,image file,Html…)

Example :

public FileResult DownloadCustomerDetails()
{
//Parameters to file are
//1. The File Path on the File Server
//2. The content type MIME type
//3. Name of file To be save by Browser
string contentType = “application/pdf”;
string filepath = AppDomain.CurrentDomain.BaseDirectory + “/FileFolder/CustomerDetails.pdf”;
return File(filepath, contentType, “CustomerDetails.pdf”);

Output:

After calling the action method in browser , the file will ask for download as shown in below

http://localhost:52877/home/DownloadCustomerDetails

}

JavaScriptResult:

  • To improve clean separation of concerns by introducing the JavaScriptResult ActionResult.
  • Release notes says, “the JavaScriptResult class is used to execute JavaScript code that is created on the server and sent to the client.”

For Example,

Controller :

public JavaScriptResult SampleJavaScriptResult()
{
var s = “alert(‘Hi’)”;
return JavaScript(s);
}

View :

<script type=”text/javascript” src=”@Url.Content(“~/Home/SampleJavaScriptResult”)”></script>

Note :

The dynamic script file will be generated based on the action name (SampleJavaScriptResult)

Output:

After press F5, it will create the dynamic script file “SampleJavaScriptResult” which will append the content from action

Then it will display the alert message which was return from the action “SampleJavaScriptResult” as show in below

REST Services (Representational state transfer)

What is REST Services :

Definition : 1

  • The REST stands for Representational State Transfer.
  • REST is a set of principles that define how Web standards, such as HTTP and URLs, are supposed to be used.

Definition : 2

In simple, REST is a architectural style construct based on the principle using the Web fundamentals.

From msdn,

  • An architectural style, sometimes called an architectural pattern, is a set of principles.
  • An architectural style improves partitioning and promotes design reuse by providing solutions to frequently recurring problems.
  • You can think of architecture styles and patterns as sets of principles that shape an application.

Let we see Fundamentals/principles details

Resource :

In REST,  every thing will be treat as resource, for example

www.aadharsh.com/image/birthday (image resource)
www.aadharsh.com/user/GKA (Dynamically pulled resource)
www.aadharsh.com/audio/audfile (audio resource)

from above, first URL shows the image resource as the output… same thing for all other URL with different identifiers. Here image/audio/video/static page… every thing are treated as resource instead of thinking physical file/data.


Unique identifier

Every resources identifies by an URL, in earlier for identify all the resource by URL.
For example to identify the user detail we use like below

www.aadharsh.com/GetUserDetails.aspx

Now in REST, added one more constrain. That is every resources  must represent by an unique URL, For example

www.aadharsh.com/GetUserDetails/Kavi
www.aadharsh.com/GetUserDetails/Gnanamurugan

Here if we want to get the user detail for the kavi then we can get GetUserDetails/Kavi in same way for other users ( we want to append username at the end) not as before like this

www.aadharsh.com/GetUserDetails?Name=Kavi
Instead of using Generic page, REST point the unique identifiers to identify the resource

Uniform Interface :

Use simple and uniform interface, for example if client want to Add/Insert/Select/Delete user detail, we use like below method name to perform the above operation

  •   AddUserDetails (it combine with PUT)
  •   InsertUserDetails (it combine with PUT)
  •   SelectUserDetails (it combine with GET)
  •   DeleteUserDetails (it combine with DELETE)

When we watch closely the method name, it seems to be inconsistent and difficult to remember,so REST says to uses simple and uniform interface. This can be obtain by the uniform methods of HTTP protocol and combine the name with the resource operation.Let we see the HTTP protocol methods

  •  GET : Get the Resource
  •  PUT : Create/Update the resource
  •  DELETE : Delete the resource
  •  POST : submit the data to the resource

Communication should be representation :

Representation is nothing but request and response between the client and the server.

Stateless :

Each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server. In simple, HTTP have nothing to indicates when a session starts or ends.

Creating Web API using MVC 4 with Razor

Here we will create simple Web API Application using MVC 4 with Razor

What is Web API?

From msdn, ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

When to use Web API?

  •    Web API when you want to create a resource based services over HTTP that can use the full features of HTTP    (like   URIs, request/response headers,various content formats).
  •   Use Web API when we want to expand service at wide way like mobile,browser,tablet…
  •   If we need a Web Service and without using SOAP, then ASP.Net Web API is best choice.

why we use Web API ?

WCF gives you the flexibility to use other protocols, but the REST implementation is a bit more complicated when compare to Web API

For Detail about REST , Go here

Example :

Step : 1

Create new project -> choose MVC Web Application and click ok

Step : 2

Next, in project template choose Web API and click ok


After creating Web API application we can see the same structure as MVC Application but in App_start, separate router file is created for Web API (that is WebApiConfig.cs) as shown below.

Step : 3

Open Values controller (which was created in default for Web API) ie., ValuesController


Here i made with simple changes like below ,

public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string

[] { “aadharsh”, “GnanamKavi” };
}
public string Get(int id)
{
if (id == 1){
return “Get value using id” +”–>”+ id;
}
if (id == 2){
return “Get value using id” + “–>” + id;
}
return null;
}
}

NOTE :

  •   In MVC Application controller implements Controller interface but in Web API controller implements      ApiController as base
  •   In web API controller, action methods are actually HTTP methods ie., GET,PUT…

Step :  4

Run the Application. When we run the Web API using below URL,

http://localhost:53934/api/Values :   The Web API route to Get() method (WebApiConfig.cs) as shown below, because there is no parameter append after the method (URL without parameter)

http://localhost:53934/api/Values/1 :  The Web API route to Get(int id) method (WebApiConfig.cs) as shown below, because there is a parameter append after the method (URL with parameter)

Note :

  • Web API is a light weight architecture and good for various device which have limited bandwidth like smart phones.
  • It also supports the MVC features such as routing, controllers, action, filter… this makes  us very simple and robust
  • Using Web API, we can get the resource in various format (like xml,json..)
  • let we see how to call PUT,DELETE methods with simple explanation

  First we want to include in web.config

<system.webServer><modules runAllManagedModulesForAllRequests=”true”></modules ></system.webServer>

then we can call using jquery (type : ‘PUT’/’DELETE’/’POST’/’GET’)

$.ajax({
url: ‘/api/Values/’ + truckId,
type: ‘PUT’,
contentType: “application/json; charset=utf-8”,
data: json,
success: function (results) {
}
});

How to create Unorderlist using HTML Helpers with custom Attribute

Creating Unorderlist using HTML Helpers with custom Attribute

Please refer to know how to use Extend HTML Helpers   here

.CS File

namespace CustomeHelpers
{
public static class CreatingUnorderedList
{
public static MvcHtmlString CreatingUnorderedListUsingAttribute(this HtmlHelper htmlHelper, string name, string value, string id)
{
var builder = new TagBuilder(“li”);
builder.Attributes

[“id”] = id;
builder.Attributes[“type”] = “radio”;
builder.Attributes[“name”] = name;
builder.Attributes[“value”] = value;
//creating Custom attribue in the Element
builder.Attributes[“listId”] = name + “-” + id;
if (id == “0”)
builder.SetInnerText(“Start List ” + id);
else if (id == “4”)
builder.SetInnerText(“End List ” + id);
else
builder.SetInnerText(“List ” + id);
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
}
}

Note : SetInnerText used for set the text/value for the element

View

<h2>Generating Unordered List using HTML Helpers</h2>
<ul>
@for (var loop_index = 0; loop_index < 5; loop_index++)
{
@Html.CreatingUnorderedListUsingAttribute(“custom_txtbox”, “Custom Helper Method”,loop_index.ToString())
}
</ul>

OUTPUT :



Below image shows  Unordered List with custom attribute listId in the li element

Server Side Model Validation in MVC 4 Razor

This article explains the ASP.NET MVC server-side validation using the Data Annotation classes. ASP.NET MVC Framework validates the data passed to the controller action and it populate ModelState with validation state based on the success/failure. Then the Model State passed object to the controller for the further process. Server side validations are play important role with sensitive information of a user.

Server Side Model Validation

  • Server side validations are required for ensuring that the received data is correct and in-valid.
  • If the received data is valid,then it will continue with further processing else show the Error message

Why we go for server-side Validation :

Some user may disable script in his browser, In this scenerio we must require to validate our data from dirty input values from the user. To avoid this we can use sever-side validation. we can validate a “MODEL”  in server-side by two ways:

  •     Model Validation with Data Annotations
  •     Explicit Model Validation

We already discussed about Model validation using Data Annotation here, so  let we discuss Explicit validation using simple registration form with user input.

Model :

public class UserRegistrationModel
{
public string UserName{get;set;}
public string Password{get;set;}
public string Address{get;set;}
public string MobileNo{get;set;}
public bool TermsAndCondtionAccepted{get;set;}
}

Controller :

public ActionResult Index(UserRegistrationModel mUserDetails)
{
if (Request.HttpMethod == "POST")
{
if (string.IsNullOrEmpty(mUserDetails.UserName))
{
ModelState.AddModelError("UserName", "Please enter your name");
}
if (!string.IsNullOrEmpty(mUserDetails.UserName))
{
Regex emailRegex = new Regex(".+@.+\..+");
if (!emailRegex.IsMatch(mUserDetails.UserName))
ModelState.AddModelError("UserName", "Please enter valid email");
}
if (string.IsNullOrEmpty(mUserDetails.Password))
{
ModelState.AddModelError("Password", "Please enter your password");
}
if (string.IsNullOrEmpty(mUserDetails.Address))
{
ModelState.AddModelError("Address", "Please enter your address");
}
if (string.IsNullOrEmpty(mUserDetails.MobileNo))
{
ModelState.AddModelError("MobileNo", "Please enter your mobile no");
}
if (!mUserDetails.TermsAndCondtionAccepted)
{
ModelState.AddModelError("TermsAndCondtionAccepted", "Please accept the terms");
}
if (ModelState.IsValid)
{
return View("SuccessfullPage");
}
else
{
return View();
}
}
return View();
}

Note :

ModelState: Gets the model state dictionary object that contains the state of the model. As per below, we can see that input values listed in the model-state.

Index :

@model ExplicitModelvalidation.Models.UserRegistrationModel
@{
ViewBag.Title = "Explicit Server Side Validation";
}
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>

<h2>Explicit Server Side Validation</h2>
@using (Html.BeginForm())
{
<fieldset><ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName, new{maxlength = 20})
@Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new{&nbsp;&nbsp; &nbsp;maxlength = 20})
@Html.ValidationMessageFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.Address)
@Html.TextAreaFor(m => m.Address, new{&nbsp;&nbsp; &nbsp;maxlength = 150})
@Html.ValidationMessageFor(m => m.Address)
</li>
<li>
@Html.LabelFor(m => m.MobileNo)
@Html.TextBoxFor(m => m.MobileNo, new{&nbsp;&nbsp; &nbsp;maxlength = 10})
@Html.ValidationMessageFor(m => m.MobileNo)
</li>
<li>
@Html.CheckBoxFor(m => m.TermsAndCondtionAccepted) I accept the terms & conditions
@Html.ValidationMessageFor(m => m.TermsAndCondtionAccepted)
</li>
</ol>
<input type="submit" value="Submit" />
</fieldset>
}

Explanation:

while pressing the submit button, it will post the data. If input data is not valid then it will add error to model-state using AddModelError() using ModelStateDictionary class

Output :

 

After pressing the submit button, it will post the data.If input data is not valid then it will show the error msg using @Html.ValidationMessageFor

Here , In controller i am using  if (Request.HttpMethod == “POST”) instead of checking ispostback. Using this we can use same action method for loading and validating using Html.BeginForm()

Caching in MVC

Different types of Caching Part 1

Why caching needed?

  • If many user are trying to accessing the site, it means your server has so many requests by the user, If every request hit the server for the response then it will lead to performance issues.
  • For example,if a page may contain some static information in your web site, in this scenario we can cache those content and don’t force your server to get them from data base in every request.This will increase your perfomance.

Advantage of Caching

  • Reduce Database and hosting server round-trips
  • Reduce network traffic
  • Improve performance

Remember while using Cache :

  • While caching of dynamic contents that change frequently, set minimum cache–expiration time.
  • Avoid caching for contents that are not accessing frequently.

Output Cache Filter :

It’s used to cache the data that is output of an action method.In default, this will cache the data upto 60 seconds.After 60 seconds, Asp.Net MVC will execute the action method again and start caching the output again.

Let we see with example..

Controller :

public class OutputCachingController : Controller
{

[OutputCache(Duration = 20, VaryByParam = “none”)]
public ActionResult Index()
{
ViewBag.CurrentDateTime = DateTime.Now.ToString();
return View();
}
}

View :

@{  ViewBag.Title = “Index”;}
<h2>Index</h2>
<h1>@ViewBag.CurrentDateTime</h1>

Run the application, first time it will show the output like below

up to 20 seconds it will show the same time in the browser without changing after we refresh the page because it will not call the action method upto 20 seconds ( so no new time updated in the viewbag)

VaryByParam : This property enables you to create different cached versions of the content when a form parameter or query string parameter varies.

VaryByParam = “aadharsh”

If it find records matching “aadharsh” string then a cache will be created,if paremeter/querystring changes than it will replace the old one with new
content

Let we discuss about Donut caching and Donut Hole caching in Part 2