Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Monday, April 27, 2015

What is Automapper?

Contents

What is Automapper ?

I have not specified mapping how does it work ?

How can we map different property names in Automapper ?

Can you give some real time scenarios of the use of Automapper ?

From where to get AutoMapper ?


What is Automapper ?


Automapper is a simple reusable component which helps you to copy data from object type to other. If you wish to get automapper read this.

For example below is a simple employee class loaded with some dummy data.
class Employee 
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public decimal Salary { get; set; }
}
// Loaded with some data
Employee emp = new Employee();
emp.FirstName = "Shiv";
emp.LastName = "Koirala";
emp.Salary = 100;
Now let’s say we want to load the above employee data in to a “Person” class object.
class Person
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
}
So normally developers end up writing mapping code as shown in the below snippet.
Person per = new Person();
per.FirstName = emp.FirstName;
per.LastName = emp.LastName;

At the first glance this does not look much of a problem but wait…think, what if you want to use this mapping code again and again.

So as a best practice you would like to centralize this mapping code and reuse this mapping code again and again. This is where our super hero “AutoMapper” comes for rescue.“Automapper” sits in between both the objects like a bridge and maps the property data of both objects.


Using Automapper is a two-stepprocess:-
  • Create the Map.
  • Use the Map so that objects can communicate.
Mapper.CreateMap(); // Create Map
Person per =  Mapper.Map(emp); // Use the map

I have not specified mapping how does it work ?


In the above example property names of both classes are same so the mapping happens automatically.

How can we map different property names in Automapper ?


If the classes have different property names then we need to use “ForMember” function to specify the mapping.
Mapper.CreateMap()
.ForMember(dest => dest.FName , opt => opt.MapFrom(src => src.FirstName))
.ForMember(dest => dest.LName , opt => opt.MapFrom(src => src.LastName));

Can you give some real time scenarios of the use of Automapper ?

  • When you are moving data from ViewModel to Model in projects like MVC.
  • When you are moving data from DTO to Model or entity objects and vice versa.

From where to get AutoMapper ?


The easiest way is to use nugget. In case you are new to nuget see this YouTube video





Or you can download the component form their main site http://automapper.org/

Thursday, November 22, 2012

C# and ASP.NET MVC (Model view controller) interview questions and answers:- What are MVC partial views and how can we call the same in MVC pages?

ASP.NET MVC (Model view controller) partial view is a reusable view (like a user control)which can be embedded inside other view. For example let's say all your pages of your site have a standard structure with left menu,header and footer as shown in the image below.



For every page you would like to reuse the left menu, header and footer controls.So you can go and create partial views for each of these items and then you call that partial view in  the  main view.

When you add a view to your project you need to check the “Create partial view” check box.



Once the partial view is created you can then call the partial view in the main view using "Html.RenderPartial" method as shown in the below code snippet'










Below is an important SQL server interview question and answers video:-




Do visit us for c#  and ASP.NET MVC interview question and answers

See more stuffs on C#/ASP.NET interview questions 

Regards,

Click here to see more C# and ASP.NET interview questions and answers

Monday, July 4, 2011

.NET and ASP.NET interview questions: Define MVC, MVP and MVVM pattern?

Answer:

MVC, MVP and MVVM are design patterns which come under the presentation pattern category and they help to remove any kind of cluttered code in UI like manipulation of user interfaces and maintaining state. Thus keeping your UI code cleaner and better to maintain.
MVC(Model view controller) pattern divides the architecture into 3 parts model, view and controller. The first request comes to the controller and the controller then decides which view to be displayed and ties up the model with the view accordingly.
MVP (Model view presenter) has the same goals as MVC i.e. separating the UI from the model. It does the same by using a presenter class. The UI talks via an interface to the presenter class and the presenter class talks with the model.
MVVM is an architectural pattern with the focus of removing UI cluttered code. It does the same by using an extra class called as view model. MVVM is mostly suitable for Silverlight and WPF projects because of the rich bindings provided by the technologies.
Following you can see step by step video to create simple application using ASP.NET MVC template:




Please click here to see more .NET/ASP.NET interview questions

Regards,

Visit Authors blog for more .NET and ASP.NET interview questions



Friday, June 17, 2011

Learn MVC (Model view controller) Step by Step in 7 days – Day 1

Contents

So, what’s the agenda?
So why MVC when ASP.Net behind code was so good?
Problem number 1:- UNIT Testing
Problem 2 :- The reality of separation of code and UI
Our HERO MVC (Model, view and controller)
Pre-requisite for MVC
Lab1:- Creating a simple hello world ASP.NET MVC Application
Video demonstration for Lab 1
Step1:- Create project

Step 2:- Add controller

Step 3:- Add View
Step 4:- Run the application
So what’s in the next Lab?
Lab2:- Passing data between controllers and views
Video demonstration for Lab 2
Step1:- Create project and set view data
Step 2:- Display view data in the view.
So what’s in the next Lab?
Lab 3:- Creating a simple model using MVC
Video demonstration for Lab 3
Step1:- Create a simple class file
Step2:- Define the controller with action
Step3:- Create strongly typed view using the class
Step 4 :- Run your application
So what’s in the next Lab?
Lab 4:- Creating simple MVC data entry screen
Video demonstration for Lab 4
Step1:- Creating your data entry ASPX page
Step2:- Creating the controller
Step3:- Create the view to display the customer object
Step 4:- Finally run the project
So what’s in the next Lab?
Lab 5:- using HTML helper to create views faster
Step 1:- Create the Customer class
Step2:- Creating the input HTML form using helper classes
Step 3:- Create a strong typed view by using the customer class
Step4:- Creating the controller class.
What’s for the second day?

So, what’s the agenda?



As the article name says learn MVC, so the agenda is simple we are going to learn ASP.NET MVC  in 7 days.
The way we will learn MVC in this series of article is by doing Labs, looking at detail steps of how to achieve those labs and also looking at demonstrative videos.




This complete article is divided in to 7 days with 42 hands on labs and every day we will do 6 labs which will help us achieve our goals.

So get ready for day 1. In day1 below is our agenda we will start with introduction, do a simple hello world and finally in the 6th lab we will create a simple customer data entry screen using HTML helper classes.






You can watch my .NET interview questions and answers videos on various sections like WCF, Silver light, LINQ, WPF, Design patterns, Entity framework etc

So why MVC when ASP.Net behind code was so good?

I am sure all ASP.NET love the behind code concept. Accepting something new like MVC will not convince them. So let’s analyze the problems with the current behind code stuff.

When we generally talk about ASP.NET application built on tiered architecture they are divided in four parts UI (ASPX pages), behind code (ASPX.CS pages), Middle tier (.NET classes) and finally Data layer.

If you see from the aspect of code distribution major code which has logic is in the middle tier or in the behind code (APX.CS files). The UI or ASPX files are HTML files which is more of UI design and data access logic are pretty much standard components like enterprise data blocks, entity data contexts etc.





Let’s try to analyze the problems.

Problem number 1:- UNIT Testing

From the aspect of unit testing we can exclude the data logic and the UI HTML. The data logic classes are already time tested components like enterprise
data block, entity data context or LINQ data context. So we really do not have to put lot of effort on testing the DAL separately. In case you have custom data access layer it will be still easy to test them as they are simple .NET classes.

There is no logic in testing on ASPX HTML as such it’s more of look and feel.

The middle tier is again a simple .NET class like data logic so you can easily do unit testing using VSTS or NUNIT.

Now comes the most important one the behind code. The behind code has lot of action and testing them is one of the most important things. The only way to invoke these codes are by doing manual test. From a longer run perspective this would not be a great choice.


Even though www.microsoft.com always boasted about how the ASP.NET behind code was separate from the UI, in practical sense it’s very difficult to decouple an ASP.NET behind code and do unit testing on them.

The ASP.NET behind code is completely tied up with ASP.NET Httpcontext object which makes unit testing very difficult.

Just think how do I unit test the below behind ASP.NET code. How do I create a Http context object , how do I simulate the sender and eventargs objects of the button clicks etc.


FYI: - Many developers would talk about mock test, rhino mocks etc but still its cryptic and the complication increases with session variables, view data objects, ASP.NET UI controls creating further confusion.



Problem 2 :- The reality of separation of code and UI

As said previously the ASPX and the ASPX.CS cannot be decoupled in reality thus reducing reusability. Yes, Microsoft did said first that the behind code is different and the UI is different but then they are probably separate physical files only and one cannot just exist without other.

For instance let’s say the same button click code when called via HTTP POST should display using displayinvoice.aspx and when called via HTTP GET should display in tree view. In other words we would like to reuse the behind code. Just think how can we do the same using the current behind code.





Our HERO MVC (Model, view and controller)

That’s where MVC comes to rescue. The behind code is moved to a simple .NET class called as controller. Any user request first comes to the controller class, the controller class then invokes the model and attaches the model to the view for display to the end user.



As this controller class is a simple .NET class we can reuse and also do unit testing easily. So let’s see how we can create MVC application using MVC template provided by visual studio.

Pre-requisite for MVC

Before we start the day lets ensure that you have all the ingredients to create a MVC application.

• Visual Studio 2010 or the free Visual Web Developer 2010 Express. These include ASP.NET MVC 2 template by default.

• Visual Studio 2008 SP1 (any edition) or the free Visual Web Developer 2008 Express with SP1. These do not include ASP.NET MVC 2 by default; you must also download and install ASP.NET MVC 2 from http://www.asp.net/mvc/ .


So once you have all your pre-requisite its time to start with the first lab.

Lab1:- Creating a simple hello world ASP.NET MVC Application

In this lab we will create a simple hello world program using MVC template.So we will create a simple controller, attach the controller to simple index.aspx page and view the display on the browser.

Video demonstration for Lab 1

In case you want spend more time with your family rather than reading the complete article you can watch the below 5 minute youtube video.




Step1:- Create project

Create a new project by selecting the MVC 2 empty web application template as shown in the below figure.





Once you click ok, you have a readymade structure with appropriate folders where
you can add controllers, models and views.



Step 2:- Add controller

So let’s go and add a new controller as shown in the below figure.




Once you add the new controller you should see some kind of code snippet as shown in the below snippet.

public class Default1Controller : Controller
{
//
// GET: /Default1/
public ActionResult Index()
{
return View();
}
}

Step 3:- Add View

Now that we have the controller we need to go and add the view. So click on the Index function which is present in the control and click on add view menu asshown in the below figure.




The add view pops up a modal box to enter view name which will be invoked when this controller is called as shown in the figure below. For now keep the view name same as the controller name and also uncheck the master page check box.



Once you click on the ok button of the view, you should see a simple ASPX page with the below HTML code snippet. In the below HTML code snippet I have added “This is my first MVC application”.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
This is my first MVC application
</div>
</body>
</html>

Step 4:- Run the application

If you do a CNTRL + F5 you should see a error as shown in the below figure.This error is obvious because we have not invoked the appropriate controller /action.



If you append the proper controller on the URL you should be able to see the proper view.



So what’s in the next Lab?

Now that we have created a simple MVC hello world, it’s time to see how we can pass data from controllers to views. The first hit comes to the controller
which will load your business objects or model and you would like to transfer these objects to the view to display them.

Lab2:- Passing data between controllers and views

The controller gets the first hit and loads the model. Most of the time we would like to pass the model to the view for display purpose.
As an ASP.NET developer your choice would be to use session variables, view state or some other ASP.NET session management object.

The problem with using ASP.NET session or view state object is the scope. ASP.NET session objects have session scope and view state has page scope. For MVC we would like to see scope limited to controller and the view. In other words we would like to maintain data when the hit comes to controller and reaches the view and after that the scope of the data should expire.


That’s where the new session management technique has been introduced in ASP.NET
MVC framework i.e. ViewData.



Video demonstration for Lab 2

Below is a simple youtube video which demonstrates the lab for view data. In this video we will see how we can share data between controller and the view
using view data. So we will create a simple controller, record the current data in a view data variable and then display the same in the view using the percentage tag.




Step1:- Create project and set view data

So the first step is to create a project and a controller. In the controller set the viewdata variable as shown in the below code snippet and kick of the view.

public class DisplayTimeController : Controller
{
//
// GET: /DisplayTime/

public ActionResult Index()
{
ViewData["CurrentTime"] = DateTime.Now.ToString();
return View();
}

}

Step 2:- Display view data in the view.

The next thing is to display data in the view by using the percentage tag. One important point to note is the view does not have a behind code. So to display the view we need to use the <%: tag in the aspx page as shown in the below code snippet.

<body>
<div>
<%: ViewData["CurrentTime"] %>
</div>
</body>

So what’s in the next Lab?

So now that we know how to pass data using view data, the next lab is to create a simple model and see all the 3 MVC entities (i.e. model, view and controller) in action.

Lab 3:- Creating a simple model using MVC

In this lab we will create a simple customer model, flourish the same with some data and display the same in a view.

Video demonstration for Lab 3

Below is a video demonstration for the same.






Step1:- Create a simple class file

The first step is to create a simple customer model which is nothing but a class with 3 properties code, name and amount. Create a simple MVC project, right click on the model folder and click on add new item as shown in the below figure.




From the templates select a simple class and name it as customer.



Create the class with 3 properties as shown in the below the code snippet.

public class Customer
{
private string _Code;
private string _Name;
private double _Amount;

public string Code
{
set
{
_Code = value;
}
get
{
return _Code;
}
}

public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}

public double Amount
{
set
{
_Amount = value;
}
get
{
return _Amount;
}
}
}


Step2:- Define the controller with action

The next step is to add the controller and create a simple action display customer as shown in the below code snippet. Import the model namespace in the controller class. In the action we created the object of the customer class, flourished with some data and passed the same to a view named as “DisplayCustomer”

public class CustomerController : Controller
{
…..
….
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = 12;
objCustomer.CustomerCode = "1001";
objCustomer.Amount = 90.34;

return View("DisplayCustomer",objCustomer);
}
}


Step3:- Create strongly typed view using the class

We need to now join the points of MVC by creating views. So right click on the view folder and click add view. You should see a drop down as shown in the below figure. Give a view name, check create a strongly typed view and bind this view to the customer class using the dropdown as shown in the below figure.




The advantage of creating a strong typed view is you can now get the properties of class in the view by typing the model and “.” as shown in the below figure.



Below is the view code which displays the customer property value. We have also put an if condition which displays the customer as privileged customer if above 100 and normal customer if below 100.

<body>
<div>
The customer id is <%= Model.Id %> <br />

The customer Code is <%= Model.CustomerCode %> <br />

<% if (Model.Amount > 100) {%>
This is a priveleged customer
<% } else{ %>
This is a normal customer
<%} %>

</div>
</body>

Step 4 :- Run your application

Now the “D” thing, hit cntrl + f5 and pat yourself for one more lab success.






So what’s in the next Lab?

In this sample we flourished the customer object from within the controller,in the next lab we will take data from an input view and display the same. Inother words we will see how to create data entry screens for accepting data from views.


Lab 4:- Creating simple MVC data entry screen

Every project small or big needs data entry screens. In this lab we will create a simple customer data entry screen as shown in the below figure using MVC template.



As soon as the end user enters details and submits data it redirects to a screen as shown below. If he entered amount is less than 100 it displays normal customer or else it displays privileged customer.





Video demonstration for Lab 4

Below is a simple video demonstration for this lab.



Step1:- Creating your data entry ASPX page

The first step is to create the data entry page using the simple HTML form action tag as shown in the below code snippet. The most important point to note in the below code snippet is that the action is pointing to the controller action i.e ‘DisplayCustomer’.
<form action="DisplayCustomer" method="post">
Enter customer id :- <input type="text" name="Id" /> <br />
Enter customer code :- <input type="text" name="CustomerCode" /><br />
Enter customer Amount :-<input type="text" name="Amount" /><br />
<input type="submit" value="Submit customer data" />
</form>

Step2:- Creating the controller

The above defined form action will post to the controller class and on the function “DisplayCustomer”. So we need to get the data from the HTML controls, flourish the object and send the object to the view.

Below is the code snippet of displaycustomer which flourishes the customer object by collecting data from request.form and sends the object to the view ‘displaycustomer.

public class CustomerController : Controller
{
…..
….
[HttpPost]
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = Convert.ToInt16(Request.Form["Id"].ToString());
objCustomer.CustomerCode = Request.Form["Id"].ToString();
objCustomer.Amount = Convert.ToDouble(Request.Form["Amount"].ToString()); ;
return View("DisplayCustomer", objCustomer);
}
}

Step3:- Create the view to display the customer object

The next step is to create the “DisplayCustomer” view.So right click on the view folder and click add view. You should see a drop down as shown in the below figure. Give a view name, check create a strongly typed view and bind this view to the customer class using the dropdown as shown in the below figure.




The advantage of creating a strong typed view is you can now get the properties of class in the view by typing the model and “.” as shown in the below figure.



Below is the view code which displays the customer property value. We have also put an if condition which displays the customer as privileged customer if above 100 and normal customer if below 100.

<body>
<div>
The customer id is <%= Model.Id %> <br />

The customer Code is <%= Model.CustomerCode %> <br />

<% if (Model.Amount > 100) {%>
This is a priveleged customer
<% } else{ %>
This is a normal customer
<%} %>

</div>
</body>

Step 4:- Finally run the project

Final step is to run the project and see the output.



You should be also able to test above 100 and below 100 scenarios





So what’s in the next Lab?

In this lab we created a simple data entry screen which helped us flourish the customer object. This customer object was then passed to the view for display.
If you closely watch the current lab we have done lot of coding i.e. creating
the HTML screens , flourishing the object etc. It would be great if there was
some kind of automation. In the next lab we see how HTML helper classes help to
minimize many of these manual coding and thus increasing productivity.

Lab 5:- using HTML helper to create views faster


In our previous lab we created a simple customer data entry screen. We completed
the lab successfully but with two big problems:-
• The complete HTML code was written manually. In other words, less productive. It’s like going back to dark ages where developers used to write HTML tags in notepad.

<form action="DisplayCustomer" method="post">
Enter customer id :- <input type="text" name="Id" /> <br />
Enter customer code :- <input type="text" name="CustomerCode" /><br />
Enter customer Amount :-<input type="text" name="Amount" /><br />
<input type="submit" value="Submit customer data" />
</form>

• Added to it lot of manual code was also written in the controller to flourish the object and send data to the MVC view.

public class CustomerController : Controller
{
…..
….
[HttpPost]
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = Convert.ToInt16(Request.Form["Id"].ToString());
objCustomer.CustomerCode = Request.Form["Id"].ToString();
objCustomer.Amount = Convert.ToDouble(Request.Form["Amount"].ToString()); ;
return View("DisplayCustomer", objCustomer);
}
}

In this lab we will see how to use MVC HTML helper classes to minimize the above manual code and increase productivity

Step 1:- Create the Customer class

Create a simple customer class , please refer Lab 5 for the same.

Step2:- Creating the input HTML form using helper classes

HTML helper classes have readymade functions by which you can create HTML controls with ease. Go to any MVC view and see the intellisense for HTML helper class you should see something as shown in the below figure.



By using HTML helper class you can create any HTML control like textbox, labels, list box etc just by invoking the appropriate function.


In order to create the form tag for HTML we need to use “Html.BeginForm” , below
goes the code snippet for the same.

<% using (Html.BeginForm("DisplayCustomer","Customer",FormMethod.Post))
{%>
-- HTML input fields will go here
<%} %>

The above code will generate the below HTML

<form action="DisplayCustomer" method="post">
…..
…..
</form>

The HTML helper “beginform” takes three input parameters action name (Method inside the controller), controller name (actual controller name) and HTTP posting methodology (Post or GET).





If you want to create a text box, simply use the “TextBox” function of html helper class as shown in the below code. In this way you can create any HTML controls using the HTML helper class functions.

Enter customer id :- <%= Html.TextBox("Id",Model)%> <br />

The above code snippet will generate the below HTML code.

Enter customer id :- <input type="text" name="Id" /> <br />

To create a data entry screen like the one shown below we need to the use the below code snippet.





<% using (Html.BeginForm("DisplayCustomer","Customer",FormMethod.Post))
{ %>
Enter customer id :- <%= Html.TextBox("Id",Model)%> <br />
Enter customer code :- <%= Html.TextBox("CustomerCode",Model) %><br />
Enter customer Amount :- <%= Html.TextBox("Amount",Model) %><br />
<input type="submit" value="Submit customer data" />
<%} %>

Step 3:- Create a strong typed view by using the customer class

So once you have created the view using the HTML helper classes it’s time to attach the customer class with view , please refer lab 5 for the same.

Step4:- Creating the controller class.

The final thing is the controller code. The controller code now becomes very simple. The customer object will be auto flourished as we have used the HTML helper classes. You will create the controller class as we did in Lab 4 but we do not need to write any kind of code for connecting the HTML screens with controller, it’s all hidden and automated.

[HttpPost]
public ActionResult DisplayCustomer(Customer obj)
{
return View(obj);
}

Enjoy your output for different condition of customer amount entered.





So have a toast of beer for completing your first day of MVC labs.



What’s for the second day?

In the next labs we will talk about URL routing, ease of MVC unit testing, MVC Controller attributes and lot more. The next lab will bit more advanced as compared to the first day, so take rest and I need to work hard to get you the second day labs.



Thursday, April 28, 2011

Comparing implementation of MVC between J2EE Struts 2 & ASP.NET MVC 2, who is the best? Part 2

So, what’s the agenda?
In case you are new to ASP.NET MVC and J2ee Struts framework

Overall Comparison with framework

Automation using template

Passing data from controller to view

Readymade folder structure

Strong type views for intellisense

Helper classes

URL customization and action mapping

URL validation

Security

Final conclusion

Thanks Vishwa



So, what’s the agenda?


In our previous article we had compared MVC implementation for J2ee and ASP.NET without using frameworks; to view comparison click ASP.NET MVC and J2ee MVC.

In today’s world no one implements MVC without help of frameworks. So it’s either ASP.NET or j2ee, framework support is a must. Struts 2 has been the most accepted framework in J2ee while in ASP.NET the ASP.NET MVC template is the king. In this article we will compare these frameworks in terms of how they differ in implementation and their positive and negative points.

In this article we will compare both frameworks using 8 agenda points: -


  • Automation

  • Passing data between controller to views

  • URL customization

  • Security

  • Folder structure management

  • Intellisense support

  • HTML automation (helper classes).


Do watch our .Net interview questions and answers video from this link
.NET interview questions and answers, you can also catch out J2ee Design pattern videos from this link Java J2ee Design pattern.


In case you are new to ASP.NET MVC and J2ee Struts framework


In case you are not aware of the frameworks you can see the below videos to just get a quick start in both the frameworks

Following is the simple ASP.NET MVC video which displays a hello world.



Following is the simple J2EE struts video to teach struts 2 with the help of an example.




Overall Comparison with framework


Before even I start below is a full comparison sheet which gives an overall view of the comparison. The same we will be discussing in more detail as we proceed in the article.




Automation using template


The first thing which caught our eyes is the Microsoft VS IDE which has a nice readymade template from where developers can start. In MVC J2ee framework the core struts framework does not have something inherent as Microsoft MVC has it.



Said and done that it does not mean J2EE community is lagging; you can still take help of open source plug-in to get the template from
http://mvcwebproject.sourceforge.net. Below is a simple snapshot of MVC web project template.

The only difference it’s not inherent like Microsoft MVC.



Conclusion: - Definitely Microsoft wins here in terms of more user friendly interfaces and automation due to the MVC template. In j2ee struts framework we need to hunt for a third party plug which will help us to achieve the same kind automation.


Passing data from controller to view


In MVC one of the most crucial parts is transferring data from controller to view. Microsoft MVC introduces a new variable called as ‘ViewData’ which will help us to transport data between controller and view as shown in the below code snippet.

The below code snippet sets data in the controller.
ViewData["CurrentTime"] = DateTime.Now.ToString();

The below code snippet displays data on the view.



J2ee Struts framework uses the HTTP request object to pass data from controller to the view. The below code snippet sets a simple date value to the request object using the ‘setAttribute’ function. In ASP.NET MVC we cannot change the request object.
request.setAttribute(“CurrentTime”,new Date());

Later we can display the data using ‘getAttribute’.





Conclusion: - First thing both the technologies have the facility of passing data, but somehow j2ee Struts framework thought process looks more convincing. At the end of the day view gets a HTTP request, so it’s more logical to pass data using the request objects rather than creating a new variable like view data for the same.

Many ASP.NET MVC fans (which includes me) can also argue logically that the request object is created by using the data sent by the end user i.e. from the browser. This data should not be allowed to be changed in between by the web application code. The request object should only be allowed to be modified by the end user using POST and GET.

For this I will give equal point to both of them for now.

Readymade folder structure


In ASP.NET MVC the template creates a readymade folder structure (they are termed as areas) which gives a developer a clear picture of where to store the model, views and controllers as shown in the below figure.



In j2EE struts framework we do not have the clear cut vocabulary for folders as we have in ASP.NET MVC. In J2EE framework the controller and model lies in Java resources folder, while the views are saved in web content folder as show in the below diagram.



Said and done you can always manually rename and create different folder structure to have the same logical representation as we have in ASP.NET MVC , only that it’s not automated.

As per our knowledge the above logical structure is not possible currently by using any J2EE struts plug-in either.

Conclusion: - ASP.NET MVC has a slight advantage in terms of better project management due to readymade logical folder structure, while in J2ee framework we need to create them manually.

Strong type views for intellisense


In ASP.NET MVC you have a nice option where you can create strongly typed view. In other words when you add a view you can select the model with which this view will connect.



Later when you go in the view and type model keyword you can get the properties of the object in a strongly typed manner.


In java we do not have the concept of strongly typed view. If you want you can set the object in request.getAttribute and then to a type cast to get the object intellisense



Conclusion: - This feature can look very exciting for ASP.NET community but it was bit amusing for my J2ee friends (I think they are right in lot of sense also). The whole purpose of strong typed views in ASP.NET MVC is for better intellisense which we can be achieved by type casting data from view data object as shown in the below figure.

The biggest problem here is that developers can start thinking that the model is tied up the view. We understand the intention is not that, but the dialog box just makes a visual intention of doing the same. The end goal of MVC is to separate the model from the view.

So concluding it’s a good feature to get maximum from less code but just that it can be confusing for junior developers who are working on MVC. For a small automation I hope we do not end with a logical confusion about MVC fundamental.

Equal points again to both. I am not giving an extra point to ASP.NET MVC as view thing is more confusing and can be achieved by typecasting.



Helper classes


A good MVC framework will always provide helper classes to create HTML code for views.

In ASP.NET MVC we have the helper classes. For instance to create a simple HTML form in ASP.NET MVC you can use the HTML helper class as shown in the below code.



In j2ee struts framework we have tag libraries which help us to generate the HTML code as it is done by using ASP.NET MVC html helper classes.



Conclusion: - Both the frameworks have HTML helper classes. Let’s not get in to which library is better or else we will lose focus on our main comparison. So even points to both the framework on this discussion.


URL customization and action mapping


MVC is all about actions and these actions are mapped to URL. As a developer you would love to see your MVC framework have the capability of customizing and configuring the MVC URL with action mapping. Below is a simple table which explains why developers would expect customization and configuration for MVC URL’s.



In ASP.NET MVC this is achieved by using the inbuilt routing mechanism. In order to configure routes you can go to the global.asx.cs code and use the routes collection to map the URL structure with the controllers and actions.
routes.MapRoute(
              "HelloWorld", // Route name
              "Pages/RegisterAction/{1}", // URL with parameters
              new { controller = "Register", action = "RegisterAction", id = UrlParameter.Optional }); // Parameter defaults


In order to configure MVC URL in J2ee struts framework we can use the Struts XML file to the same. The below mapping is more clean than the routing collection of ASP.NET MVC. In J2ee framework we can see the mappings more better as they are mapped directly to page names.



Conclusion: - J2ee Struts framework definitely wins in terms of MVC URL configuration and mapping to the controller as its defined using XML file. This thing can be really improved in ASP.NET MVC framework. To change the mapping compiling code is more of a burden.

URL validation


In ASP.NET MVC we have the advantage of doing URL validation using regex (regular expression) before the action hits the controller. For instance below is a simple validation where before the view customer action is called we can check that the input to the action is only numeric value with 2 digits.
routes.MapRoute(
              "View", // Route name
              "View/ViewCustomer/{id}", // URL with parameters
              new { controller = "Customer", action = "DisplayCustomer", id = 0 }, new { id = @"\d{1,2}" }
);


Currently J2ee struts framework does not support the same, said and done you can always still do validation after hitting the controller using some custom logic.

Conclusion: - This is definitely a plus point for ASP.NET MVC because MVC URL’s can be invoked from any medium, via browser, via URLs etc. So we would like to ensure that appropriate validation is checked much before it hits the controller.

Security


MVC URL’s are mapped to action and they can be invoked directly which also means that they are subjected to cross site attacks, sql injection etc. ASP.NET MVC framework has provided security attributes by which we can protect our URL from such attacks.

For instance to prevent forgery attacks and cross site scripting attacks we can use the ‘HtmLAntiForgeryToken()’ as shown in the below code snippet.



In the actions later you can then check if there was any violation.
[HttpPost] [ValidateAntiForgeryToken]
public ActionResult Delete(int customerid)
{

}

You can also mark the controller by using validate input attribute to avoid CSS.
[ValidateInput(true)]
public class OurController : Controller

Critical functions on which you do not want actions to be invoked you can mark the methods as ‘nonaction’ as shown in the below code snippet.
[NonAction]
public void DoPasswordChange(string username, string newpassword)
{
   /* Rest of code unchanged */
}

In J2ee Struts framework currently we do not have any inherent security function to achieve the same. Some customized code.

Conclusion: - This is the biggest win for ASP.NET MVC framework security. Hope that J2ee struts framework in coming times has such kind of inherent security feature which will be a great extra added advantage for the framework.


Final conclusion


Below is the final conclusion. ASP.NET MVC framework out performs J2ee in 4 things while J2ee has the flexible XML URL customization which is currently not available in ASP.NET MVC. For all the other points both of them remain on the same page.

I have tried my level best to put forward both the sides and while doing so I never had in my mind that I am an ASP.NET Microsoft MVP and I should hard sell ASP.NET MVC framework. I have made by best effort to make a true comparison and see which one of them is the best. I do understand how every developer loves his technology, by any chance I have hurted….BIG SORRY.



Thanks Vishwa


Special thanks to Mr Vishwanathan Narayanan who helped me to give inputs on the J2EE side without which I would not have achieved the same. You can see his Java and j2ee design patterns videos by clicking on Java J2ee Design pattern videos.