Programming Training | New Way New Style
A Step-by-Step ASP.NET Tutorial for Beginners - blog.udemy.com
MAHAK: Society to Support Children, Suffering from Cancer
Read Valuable Verse From Cosmic References Quran & Bible

MVC

Mahsa Hassankashi | Saturday 9 2014 1:30


MVC from Basic



Why MVC and What is MVC?    MVC Sample File.zip   This source sample is based on MVC 4.0

It   just take 50 minutes of your time to understand fundamental MVC concepts


We have Web Form .cs or .vb so why we need MVC?

Look at below pictures, they are about WebForm.aspx, they include two main part

1.WebForm.aspx -> For .Net Controls such as user input (TextBox, ComboBox & etc) is located here, also output (ListView, GridView,..)

2. WebForm.aspx.cs -> For code behind, connection to Business Logic then Data Access Layer, and any code which programmer like to put would be located here.




Assume you need to change your interface dramatically way so you have to change all of your codes which are in WebForm.aspx.cs or your modification is just tiny but you need to change again your .cs file, both of WebForm.aspx and WebForm.aspx.cs stick to each other and changing one of them force us to change other one. Absolutely you know about changing in code it has so many errors, bugs and in worse situation you even have to change your logic throughout the entire solution and project.

In Mode View Controller we will separate these two part from each other:

1. Business Logic -> Model

2. WebForm.aspx   ->  View

3. WebForm.aspx.cs -> Controller



So whenever you need to change View you do not have to change your code in Controller or reversely. It is so

1.Modular

2.Scalable

3.Extensible

4.Reusable

5.Flexible

6.Easier to test ( Unit Test )

In follow steps I tried to define complete project and whenever I encountered new concept I made it red color with underline and then expanded its features: I think this way make learning MVC easier and map it with old concept that you know from before.

You can catch

1.Simple Data Entry +  Validation + ViewData + TempData + ViewBag + Querystring + HiddenField 

2.Item List ( all of items )  as View Result

3.Item List ( according to specific ID ) as View Result

4.Routing -> set as start up page in ASP.NET

5.Hyper link

6.Ajax as JSON result

7.Partial Views & _Layout.cshtml as masterpage

8.Action Filter


Step 1: Create New MVC Project in Visual Studio 2012


File -> New Project -> .Net  framework 4.5 -> ASP.NET MVC  4 Web Application C#

Define Name, Location and Solution Name -> Click on OK



Step 2: Select Razor view instead of ASPX


Project Template -> Select Template -> Empty -> View Engine: Razor

We have two View Engine:

1.ASPX : Heavy Weight for Render                , Complicated Syntax for programmer  <%=variable%>

2.Razor : Light Weight for Render                 , Simple  Syntax for programmer @variable


Razor View Enging:

Totally in razor you should use @ whenever you want to write codes except from html tag although these codes include Html.Displayfor you should use @ Html.DisplayFor(“Name”)





Step 3: Create Appropriate Data Base for this Scenario (Create Product Table)


Open Microsoft SQL Server Management Studio -> Create New Data Base -> Add New Table -> Name : Product


Column Name                                     Data Type                                               Allow Nulls

ID (PK)                      int(identity=yes, increment and seed=1)                                  No

Name                                                  nvarchar(100)                                            Yes

Price                                                   numeric(18, 0)                                           Yes







Step 4: Create Data Model by Entity Data Model


Entity Frame work for data modeling


Project Name ( Right Click ) -> Add -> New Item -> ADO.NET Entity Data Model -> Name: Model1.edmx

-> Click Add -> Entity Data Model Wizard : Model Content: Select  “ Generate From Data Base ” -> Click Next




Choose your Data Connection : Click on New Connection -> Data Source:  Microsoft SQL Server -> Click Continue



Server Name: Local (.) -> select Data Base Name and then Click Ok and next window Click Next




Select table which you want to use it in your project.



Finally Click on Finish

In the response of Security Warning Press Ok





Now you have model1.edmx in your solution and in the next articles I will explain this entity frame work.




Step 5: create Model


Model Folder (RC) -> Add -> Class






Define inside your product class your data model


Step 6: Define Validation inside Model


Validation:

You just need to define attribute such as [Require] above any of your property and force it to be filled in a validation control, you need add using System.ComponentModel.DataAnnotations;


Required                                                                         must be filled and does not have to be empty

StringLength (X)                                                               X is based on the length of string

RegularExpression (@”[A-Za-z0-9-+*/%$]”)                         all of character between A to Z and a to z ,0-9

Range(X,Y)                                                                      numeric between X and Y

Compare such as password and confirm password                  comparing two character if are same or not   




  


Step 7: Create Controller 


Adding Controller

Controller folder (RC) -> Add -> Controller -> Name: ProductController




Make an Action Result and name it “CreateView”




Data Entry by MVC in a nutshell


SimpleMVCTutorial



Step 8: Master page and Partial Views


Organize Views as master or layout and partial views:

Assume you want to create web page such as below picture, you need a container to keep header, body and footer inside itself “_Layout.cshtml” as master page is responsible for this role, due to you need to fix header and footer inside all of your web page and both of them are same in all pages so you should create them separately as partial view and then assign these partial to your “_Layout.cshtml” as master page, then create all of your view and inherit later view from your “_Layout.cshtml”.




In MVC we have _Layout.cshtml instead of master page in ASP.NET


Step 8.1: Create "_Layout.cshtml" as Master Page

On Views Folder Right Click -> Add -> New Folder -> Name: Shared

On View Folder expand Shared Folder Right Click -> Add -> View ->




View Name : “_Layout.cshtml” -> View Engine: Razor -> Unchecked all checked Box -> click Add

“_Layout.cshtml” is playing important role as Master Page in ASP.NET

Clear and remove layout=null from above of this view and insert @using System.Web.Mvc




Step 8.2: Create Header and Footer (Partial Views) as Fix part of Master Page

Now this is time for making “_Header.cshtml” and “_Footer.cshtml”

Views folder -> on Shared Folder -> Add -> View -> View Name: _Header -> Check Create as Partial View





Inside these view just write as follow:




Step 8.3:  Create "_ViewStart.cshtml" Startup page


Making starter View:

On Views Folder Right Click and -> Add new View






Name it: “_ViewStart.cshtml”

Clear anything and make it like below picture:





Organize Master Page MVC in a Nutshell


BriefDescMVCMasterPage


Step 9: Create View for Data Entry by Right Click on Action and Select Add View


Now it is time to make the first view which is derived from master page or _Layout.cshtml

Go on Product Controller ->  (RC) on Action Name  (CreateView) -> Add View

[use action as methods or events write your codes here and for each action you can make one view by right click on its name and select Add view ]





Before checking check box on below screen be sure about you (Build)  complied your project to show all models here.


Check Create a Strongly-typed View and select Product Model from that

Then select Scaffold Template as Create to have easier way to design your page, it will add automatically fields from your model,  I did not use model here and I just referred this view to entity, later in complicated scenario which I need to insert record to two or three tables I will use view model , repository and auto map. 

Then check use a layout or master page and select “_layout.cshtml”








Now we have something like below picture: (You do not have to write all of these html code you just need select your suitable scaffold to create appropriate html code according to your model) . Here you choose "Create" due to you need add product name and price to your table so select "Create" in order to have this view.





Change it like that:

For transfer your fields (Product Name and Product Price info) from view to controller in order to insert them into table, write  inside html.beginform(“Action Name”, “Controller Name”, FormMethod.Post)

It will send field as model “Product” to controller



On the other side in your controller you should use [HttPost] attribute in order to get information from view as a product model which is argument in Create action.




Step 10: Create View for show Product List


Now it is time to show data from view and get data from data base and show them. Make index action and right click on index action and create index view. This time select "List" for scaffold. Write inside Index Action below Code:

     At first make ctx from your DBContext

     At Secound return your table as list to view.







Brief Desc MVC Iterate Item





By now we did illustrate data, so in this step I want to explain how to get data from view to create new record in data base






For edit action, delete action and details all things are similar. I just mention to some points here:




We learned how to transfer data from model to view or controller, but

How to transfer data between View and Controller?





TransferData From Controller To View & View To Controller & Controller ToController


MVC Tutorial-Transfer Data Between Controller and View



Routing in MVC to determine which action from which controller should be start, it works as “set as startup page” in ASP.NET




To use sample file double click on mvc icon then attach data base file and use sample files:



In next articles I will describe

1.       “Json” , “Ajax” in mvc

2.       Querystring

3.       Hiddenfields

4.       Viewmodel

5.       Repository

6.       Automapper

7.       Action Filter

8.       Authorization

9.       Bundling

10.     Unit Test




MVC Sample File.zip  




Tag: ,, , , , , ,

Rss Feed

Feedback: Feel free to leave any feedback on this article; it is a pleasure to see your comments about this code. If you have any questions, please do not hesitate to ask me here.
Your email address will not be published. All fields are Required





Darsh | Friday 9 2014 23:16
Great
Justin Long | Saturday 9 2014 15:16
This article is VERY had to follow. between the constant torrent of over-sized images and the broken English. I'd consider writing this in your native tongue instead. and consider using lists when explaining steps. What about bolding certain things? such as: Check the STRONGLY TYPED (in bold) checkbox. Makes it much more readable. There's some conventions being broken here as well in your code.. As well as some mis-understandings of what the framework is doing. But not TOO important at this stage of article.
Mahsa Hassankashi | Saturday 9 2014 15:31
Hi @Justin Thank you for your dedicate comments, about image size you are right, but unfortunately I could not get it about BOLD and Broken English. I wrote it for beginners and I had to determine new data type and use at least sentence as possible as.
Hasan Habib | Sunday 9 2014 12:58
When I start reading I thought, This is a what I am looking for, But when i went to middle of the article I just lost. Feel hard to follow and some place not understand why need to do it, more explanation required. :(
Mahsa Hassankashi | Sunday 9 2014 13:7
Hi @Hasan Thank you for your comment, maybe ASAP I will add more details among pictures, but is is possible tell me where exactly did not you understand?
Hasan Habib | Sunday 9 2014 22:8
it will be good u put a list in middle like a cooking recipe with all the page or class name we require to build the MVC site.
Mahsa Hassankashi | Monday 9 2014 0:2
Hi @Hasan Thank you for your comment, It is very helpful , I will do your idea in a table template ASAP.
Kleber | Tuesday 9 2014 9:44
Hello Mahsa okay ?! I'll be waiting for the next articles about MVC, and congratulations again for this article, GREAT Article. Kleber.
Mahsa Hassankashi | Tuesday 9 2014 10:1
Hello Dear Kleber Thank you so much for your words. Ok I am making its source sample and ASAP I will publish it and inform you. Best Regards. Mahsa.H
Mohammed Gadi | Friday 9 2014 9:26
Hello Mam Thanks For Ur Dedicated work for the beginners..But I want to ask u that can't we build chat app in ASP.net webforms Instead of using MVC model?
Ravi | Thursday 10 2014 23:17
@Hasan: Great article for beginners .thanks you for sharing. i will be waiting for the next article on JSON,AJax,webgrid,IOC
Mahsa Hassankashi | Friday 10 2014 14:24
Hi @Ravi, you`re welcome, surly I am writing another articles and at this moment I am writing article about Data Access Layer that is the fundamental for all of developers, I am at the end of that: http://technical.cosmicverse.info/Article/Index/4 I will wrap up it as soon as possible.
Mahsa Hassankashi | Friday 10 2014 14:35
Hi @Mohammed Gadi, You`re welcome. Yes you can build SignalR with ASP.Net instead of MVC.
Erald | Monday 11 2014 8:38
Excellent explanation of MVC archtiecture. Well done! Easy to follow with VS2012 and SqlServer 2008. I hope in your spare time you could build/publish another MVC article but with AREAS included in the project. Greetings from Albania! - Erald
Mahsa Hassankashi | Tuesday 11 2014 4:53
Hi Dear @Erald Thank you so much for your motivated words. I will try my best to publish another MVC article which contains important topic from MVC. Best Regards.
Matt | Sunday 11 2014 21:1
This is a good, no nonsense intro to making a basic data driven application in asp.net MVC. My only constructive criticism is that you might seek out a native English speaker to clarify some of your instructions. It's not absolutely necessary as I was able to follow your article as-is, but it would make your article need more professional. Also, you might try re-formatting the article to make it a little easier on the eyes. Your substance is all there! You just need a little bit more attention to style to make this a first class tutorial!
Sadegh | Saturday 12 2014 10:1
Very Good Your Post
adeeb | Wednesday 12 2014 22:48
can i know where are the next articles(Json” , “Ajax” in mvc 2.Querystring3.Hiddenfields 4.Viewmodel 5.Repository 6.Automapper 7.Action Filter 8.Authorization 9.Bundling 10.Unit Test.and i your website why wcf and jquery links are not performing ant action.
adeeb | Wednesday 12 2014 22:54
Really I want to say one thing from my bottom of the heart.You are inspirable.Your website representing what you are.Your kindfull.Your the person thought and indeed.
Mahsa Hassankashi | Thursday 12 2014 5:4
Hi @Matt Thank you so much for your comment and your constructive advice. You are right and I will change format and improve language. Unfortunately I miss your email, please send your email in order to inform you better article from this website.
Mahsa Hassankashi | Thursday 12 2014 5:7
Hi @Sadegh thank you so much for your comment.
Mahsa Hassankashi | Thursday 12 2014 5:12
Hi @Adeeb, thank you so much for your comment, I will be so happy if I can help. That is nice of you. I promise you in near days I publish MVC advanced and some other subject such as WCF, Jquery, Design Pattern, SQL and other concept in C#. I am a little busy now but I try my best to complete these concept by 10 days.
Inam Abbas | Tuesday 1 2015 3:6
it very good Article if any One can learn from this
harsha | Thursday 1 2015 18:17
With these articles You clearly save 50% of any company's fresher training programs to get them to advanced levels :) What else can I say !? Go Green Lady ! -Harsha
Gajendra Pawar | Thursday 1 2015 23:24
i am very pleasant when read your article and implemented all the step which is describe by you in your article.i'm beginner level programmer to learn MVC, so thank you for such a good article it's really helping for me.Keep do great work . :)
Mahsa Hassankashi | Friday 1 2015 5:48
Hello Dear @Harsha , Thank you so much for your NICE comment, I hope I can put more advanced concept (the rest of 50%) here in order to free and online knowledge become available for all the developers throughout the world.
Mahsa Hassankashi | Friday 1 2015 5:51
Hello Dear @Gajendra Pawar, I am so glad to hear it that you improved your MVC by this, I try my best to extend web site. Thank you so much for your comment.
Unknown | Thursday 2 2015 2:18
Excellent post, very informative. I wonder why the other specialists of this sector do not notice this. You should continue your writing. I am confident, you have a huge readers base already!
Unknown | Thursday 2 2015 13:4
I have recently started a blog, the info you provide on this website has helped me tremendously. Thanks for all of your time & work.
Mahsa Hassankashi | Sunday 2 2015 10:4
Dear @Unknown Thank you so much for your nice and kind manner and words. I wish to know your email.BTW You are most welcome to this web site.
sulmaz saba | Saturday 3 2015 21:29
hi,thanks for your article ,that was great but i have problem at step 9,where did action come from?
Mahsa Hassankashi | Wednesday 5 2015 13:42
Hello Dear @Sulmaz Saba , thank you for your comment. Sorry for delay in response please pay attention to my first lines "Go on Product Controller -> (RC) on Action Name (CreateView) -> Add View" You should Go to Controller Folder in your solution and then select "ProductController.cs" file and then write an Action body such as you see in my sample as "CreateView" and right click on it. I hope it helps you. Otherwise please do not hesitate to share your question here.
Pranav Patel | Friday 5 2015 3:14
thank you for such a very useful article.. it really helped me in my college project and presentation
Krunal | Friday 5 2015 3:15
awesome
Mahsa Hassankashi | Friday 5 2015 15:41
Hi Dear @Pranav Patel You are most welcome in site. It is my pleasure to hear you that it is helpful for you and your colleague.
Mahsa Hassankashi | Friday 5 2015 15:43
Thank you so much Dear @Krunal for your comment.
Rainer Martin | Saturday 6 2015 21:31
In The Name of God. Very clear. Thanx
vignesh | Friday 7 2015 3:17
hi Mahsa Hassankashi, your article as very usefull for who are beginners in MVC