All posts by Thiyagu

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.

ExplictValidationController

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

NonActionAttribute Class in MVC

What is NonAction Attribute ?

In ASP.NET MVC, every public method of controller is accessible through the url regardless of return type. If we create any public method in the controller which is not intend to response as like action method. But it also accessible through the browser ULR. To overcome this scenario, the NonAction attribute has introduced

“All methods in MVC are treated as a action method. “

Purpose of using :

  •  As per above statement, all public methods of a controller class are basically treated as action methods in Asp .Net MVC. The methods which are
  •  By using this we changing the default behavior.

Example

Both GetUserDetail are treated as action methods.

public ActionResult GetUserDetail(){
// some code inside here
return View();
}

public void GetUserDetail(){
// some code inside here
}

So overcome this we are using NonAction Attribute method

[NonAction]
public void GetUserDetail(){
// some code inside here
}

[NonAction]
public ActionResult GetUserDetail(){
// some code inside here
return View();
}

Now above two methods are treated as Non action method. 

Child Action Attribute in ASP.NET MVC 4

What is ChildActionOnly?

The ChildActionOnly attribute ensures that an action method can be called only as a child method from within a view. In simple, ChildActionOnly attribute make controller action method to consider as non-action methods (It treated as normal method).

Where to use ChildActionOnly?

  • ChildActionOnly it related with partial views but it is not compulsory. If decided not to access through url then we may declare action method as ChildActionOnly.
  • This attribute used to prevent the action method being invoked as a result of a user request, that is it prevent from accessing via url.

Creating a Child Action Method

Let we discuss with example,

public class ChildActionTestingController : Controller
{

[ChildActionOnly]
public ActionResult GetUserDetails(int userId)
{
//Your Logic Here !!!
return PartialView(“GetUserDetails”, null);
}
}

Here GetUserDetails method is non-action method. The GetUserDetails method cant able to access by URL like ChildActionTesting/GetUserDetails.

@Html.Action(“GetUserDetails”, “ChildActionTesting”)

After declare GetUserDetails as childactiononly attribute, then it can’t allow to access through url. If you try to access, it show the error msg like below. It will treat as a normal method.

“The action ‘GetUserDetails’ is accessible only by a child request.”

Using an Asynchronous Controller in ASP.NET MVC 4

Asynchronous controller enables us to create asynchronous action methods in our application. This allows us to perform long running operation without making the running thread idle. Asynchronous action methods are useful when an action must perform several independent long running operations.

Synchronous

In Synchronous, if you making request, then you will have to wait till the response, you may not do other process until it response.

Asynchronous

In Asynchronous , if you making request, then you don’t need to wait for the response and we can perform any other process/task. Whenever the response arrive, you can receive in call back delegate.

What is Thread starvation in WebServer ?

  • From above, the request from Request A, Request B are accepted and processing but Request C not able to get the thread because the size of the pool is 2 so this situation is called thread starvation.
  • In this case we may get Server Busy Error

As per MSDN, When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is blocked while the request is being processed, and that thread cannot service another request.

This might not be a problem, because the thread pool can be made large enough to accommodate many blocked threads. However, the number of threads in the thread pool is limited. In large applications that process multiple simultaneous long-running requests, all available threads might be blocked. This condition is known as thread starvation

If you have multiple long-running requests, all available threads might be blocked and the Web server rejects any additional request with an HTTP 503 status

(Server Too Busy).

To overcome this, ASP.NET MVC provide asynchronously call in controller/action

Here let we see the asynController

How to convert controller to asynchronously

To convert a synchronous action method to an asynchronous action method involves the following steps:
1) Before we deriving the controller from Controller, now we want to derive it from AsyncController. Controllers that derive from AsyncController enable

ASP.NET to process asynchronous requests, and they can still service synchronous action methods.

Example

We want to apply “Async” before controller like

public class AsynchronuosController : AsyncController

The “OutstandingOperations” property tells ASP.NET about how many operations are pending. It is needed because ASP.NET dont known how many operations were initiated by the action method or when those operations are complete. When OutstandingOperations property is zero, ASP.NET completes its process by(asynchronous operation) calling the Completed method.

Example

AsyncManager.OutstandingOperations.Increment();
AsyncManager.OutstandingOperations.Decrement();

If we calling two method inside the action then we want to increment by 2 (AsyncManager.OutstandingOperations.Increment(2))

Sample Program:

using System.Web.Mvc;
using System.Threading;

namespace Asynchronous_Controller.Controllers
{
public class AsynchronuosController : AsyncController
{
public void IndexAsync()
{
AsyncManager.OutstandingOperations.Increment(2);
Call1();
Call2();
}
public ActionResult IndexCompleted(string call1, string call2)
{
ViewData["Call1"] = call1;
ViewData["Call2"] = call2;
return View("Index");
}
void Call1()
{
Thread.Sleep(5000);
AsyncManager.Parameters["Call1"] = "call1";
AsyncManager.OutstandingOperations.Decrement();
}
void Call2()
{
AsyncManager.Parameters["Call2"] = "call2";
AsyncManager.OutstandingOperations.Decrement();
}
}
}

 

Creating Scaffolding template for Cutom Model

Creating Custom Scaffolding

What is Scaffolding in MVC

Scaffolding is a Templates for Create, Delete, Edit ,Details. It will reduce the time for developer for creating controller,view for the specific model
This is a Scaffolding package for ASP.NET which is installed via NuGet using ‘Install-Package MvcScaffolding’ command

Using Templates

Step : 1

Create Sample web project

Step : 2

Create custom model as like below

Step : 3

Here we going to install the scaffolding in our project.
GoTo Tools –> Library Package Manager –> Package Manager Console as shown below to install the scaffolding

To install Scaffolding, type below command in below console
cmd : Install-Package MvcScaffolding

Step : 4

Next creating template against custom model by using below command

cmd : Scaffold controller EmployeeModel


After executing the command in console, it will create the template for CRUD Operation as shown below

 

Output :

After generation of Views, run the application. Now u can perform CURD Operation without extra code.

Difference between POCO and DTO model

Really, I spend more time to understand Poco and DTO with a lot of confusion and questions. After understanding I decide to post immediately to my blog.

What is POCO?

  • POCO stands for Plain Old CLR Object.It provides freedom to define an object model in which objects does not inherit from specific base classes
  • POCO data classes, also known as persistence-ignorant objects, it refers to an object do not have any persistence concerns
  • It mainly has a control over implementation and design
  • A POCO is a BO (Business object). We can implement validation and any other business logic can occur here.
  • POCO have state and behavior.

What is Persistence ignorance in POCO

It means (layers) it does not depend on the design of the database, IE., type of database, type of database object.

Example for POCO Model

public class Customer {
public int CustomerID
{ get; set; }
public string CustomerName
{ get; set; }
public string CustomerGender
{ get; set; }
}

What is DTO?

  • Stands for Data Transfer Object, its Main purpose is to transfer data.
  • It just stores data. It is a lightweight container used for transferring data between layers.
  • There will be no effect on application if entity changed or modified (based on the Database structure)

Example for DTO Model

public Customer()
{
CustomerID = Int_NullValue;
CustomerName= String_NullValue;
CustomerGender = String_NullValue;
Address = String_NullValue;
}
Difference between POCO and DTD

  • POCO has state and behavior, but DTD has only state (it does not contain behavior IE., method)
  • POCO describes an approach to programming, where DTO is a pattern that is used to move data using objects.

How to Apply Styles with Html Helpers in MVC4 Razor

How to Apply Styles with Html Helpers in MVC4 Razor

In this article let us discuss how to apply CSS styles using HTML helpers.

  • using Inline
  • using Class

Using Inline CSS

From the below code, we can directly add the styles.

@Html.TextBox(“Name”, “”, new{style = “width:80px;height:20px;background-color:#F0F0F0 ;”})

using CSS Class

Another way, we can call the css class name instead of style.

.txtbox {
width: 100px;
height: 75px;
background-color: #F0F0F0;
border:1px solid black;
}

@Html.TextBox(“txtName”,””, new{@class = “txtbox”})

Note :

Correct Way:

@Html.TextBox(“txtName”,””, new{@class = “txtbox”})

Wrong Way:

@Html.TextBox(“txtName”, new{@class = “txtbox”}) – It will not apply the style to the textbox

From the above code new{@class = “txtbox”} want to be third parameter , if you not going to pass the value as second parameter then we need pass null/Empty value.

Output:

MVC Razor : Different way of getting @Html.TextBox value from view to controller

In this article we are going to discuss about the different way of getting the value from the textbox using MVC razor.

Index.cshtml

Here we had included the Html.TextBox in the Index.cshtml.

<div>
@using (Html.BeginForm(“Index”, “Index”, FormMethod.Post))
{
@Html.Label(“Enter Your Name”)
@Html.TextBox(“txtName“)
<input type=”submit” id=”btnSubmit” name=”Submit” />
}
@ViewBag.Name
</div>

Method 1: Using the Name(id) of the @Html.TextBox

IndexController :

We having a Index action method for getting the textbox value from the view.

public ActionResult Index(string txtName)
{
ViewBag.Name = txtName;
return View();
}

  • In this method we can get the value of textbox  using id/name. ie., txtName.
  • Getting value type must be string, else it will show the following error ( if we change type to int)

Method 2: Using the FormCollection

FormCollection does not contain key/value pairs, just having an id/name. Using the name/id of the text box we can get the value as shown below..

public ActionResult Index(FormCollection Form)
{
ViewBag.Name = Form[“txtName”];
return View();
}

Below image shows quick view of formcollection

 

Keep cool coding….

How to handle Multiple submit buttons in the same form/page

Handle Multiple submit buttons in single page

Scenario :

For example, we have a login form with “sign in”,”sign up” and “cancel” button. In this scenario, “sign in” will redirect/do some action,same like sign up and cancel. Lets we discuss how to handle multiple button in same form (calling different action method).

View :

Let we create view with three submit button.

Controller

Here i am going to create three separate action method for signin,signup,cancel for capture the click event in the controller.

[HttpPost] [MultipleButton(Name = "action", Arg= "signin")] public ActionResult signin() { return RedirectToAction("Index", "signin"); }
[HttpPost]
[MultipleButton(Name = "action", Arg= "Signup")]
public ActionResult Signup()
{
return RedirectToAction("Index", "Signup");
}
[HttpPost]
[MultipleButton(Name = "action", Arg= "Cancel")]
public ActionResult Cancel()
{
return RedirectToAction("Index", "Home");
}

Custom ActionNameSelectorAttribute  :

Here we going to implement a custom ActionMethodSelectorAttribute to check which button submitted the form.This contains values posted in the form in a NameValueCollection object.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultipleButtonAttribute : ActionNameSelectorAttribute
{
public string Name{get;set;}
public string Arg{get;set;}
public override bool IsValidName(ControllerContext controllerContext,
string actionName, MethodInfo methodInfo)
{
bool isValidName = false;
string keyValue = string.Format("{0}:{1}", Name, Arg);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
if (value != null)
{
controllerContext.Controller.ControllerContext.RouteData.Values[Name] = value;
isValidName = true;
}
return isValidName;
}
}

Note : While clicking the button, MultipleButtonAttribute method will execute first to know which action Mthod to call

OUTPUT :