All posts by Thiyagu

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 :

How to use MVC Bind Attributes

 

What is Attributes ?

Attributes are classes that allow you to add additional information to elements of your class structure.

What is Bind Attributes ?

In ASP.NET MVC View that accepts user input and post information to a server. Bind Attribute allow  an option to restrict the properties(ie., model) that are allowed to be bound automatically.

Where can we use Bind Attributes ? :

Scenario :

For example we having model/properties for binding the EMP DETAILS as shown below

Model :

public class EmployeeDetail
{
public string EmpName {get;set;}
public string EmpAddress {get;set;}
public string Department {get;set;}
}

From above some employee have rights to enter Department but some employee not have such rights to add Department.  In such scenario we can easily do it form level by hiding the Department Details from the page/Separate page, In this scenario we can use Bind Attribute to eliminate this property to update in Model/Property/DB.

Example : We can achieve this in two ways

1) Handel in Action Level

2) Handel in Model Level

Let we discuss about Action Level :

In Action Level, we will restrict the property while receiving to method ( it will not filter in model)

controller :

In controller we can restrict particular property (department) as shown below

public class EmployeeDetailController : Controller
{

[HttpPost]
public JsonResult Save([Bind(Exclude = “Department”)] EmployeeDetail emp)
{
return Json(string.Format(“EMP DETAIL”, emp));
}
}

view

@using (Html.BeginForm(“Save”, “EmployeeDetail”, FormMethod.Post, new
{
@id = “saveEmpDetails”
}))
{
@Html.TextBoxFor(m => m.EmpName)
@Html.TextBoxFor(m => m.EmpAddress)
@Html.TextBoxFor(m => m.Department)
<input type=”submit” value=”Insert” name=”Insertaction”/>
}

OUTPUT :



Click insert button to view in debug mode, as shown In below the model restrict to bind the value for the Department.


Let we discuss about Model Level Restriction :

We can handel in Model as shown below

[Bind(Exclude = “Department”)]
public class EmployeeDetail
{
public string EmpName{get;set;}
public string EmpAddress{get;set;}
public string Department{get;set;}
}


NOTE :

  • Attribute will be executed before the action
  •  If we place [Bind(Exclude = “Department”)] above the class it will exclude Department from other class inside the particular Model page
  •  If we place it inside the class it will applicable to particular class



How to create Areas in MVC 4 with Razor

 How to use MVC Areas feature using Razor

 What is Areas ?

  •  In MVC we have default folders (view, model, controller…) structure, If application grew larger, then it will be complicated to maintain a modules and structure logic for the file in the solution.
  •  To overcome this, MVC provide areas,Using MVC area has its own folder structure which allow us to keep separate controllers, views, and models…

Creating Areas

Step 1:

To add an area to application, right-click on the project —> select Add —> Area option as shown below.

Step 2:

Enter the Module/Areas Name in the “Add name Prombt” as shown below

Click ADD button to create  structure(Areas) as shown below

Same way we can create more areas based on our modules…

Step 3:

Create Controller by right clicking the controllers folder then create view , as shown in below

Step 4:

Here we start discuss about “How to call Module_1(Areas) from main project”.

Here i am creating actionlink for calling the view inside the Module_1

@Html.ActionLink(“Go to Module-1 Index”,”Index”,”Module_1″,new {area =”Module_1″},null)

  • “Go to Module-1 Index” :   Name of link
  • Index : Name of the Action
  • Module_1 : Name of the controller
  • new {area =”Module_1″} : Name of the area

Step 5 :  Run the Application

OUTPUT :

By clicking the link, it will redirect to Module_1 (inside the Areas) as shown below