Sunday, March 13, 2011

Learning ASP.Net MVC 3


An excellent step-by-step tutorial by Scott Hanselman Reference:
 "http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part1-cs"


It is very good resource for the people who wants to move from ASP classic to ASP.Net …


Using New Project  “ASP.Net MVC 3 Web Application “  creates the MVC code:

  1.     Controller folder containing the Controllers 
  2.    View folder containing the view Templates
  3.    Model folder would contain the Models



Controllers are the link between Views and the Models.


In the HomeController, which is created by default by convention  invoked when we request,


<>/home


HomeController has multiple actions,


<>/home/index is the default action


<>/home/about would invoke About() action in the Controller class.


A typical action would return a View() which is mapped with View Template (About.cshtml) in the Views folder default named after the Action name.


About.cshtml will have all the HTML tags and embedded scripts like; @ViewBag, @HTML, @URL, @RenderBody etc. for displaying the dynamic content.


Controller can pass data to the view using,
ViewBag.Message = "Hello " + name; 
ViewBag.NumTimes = numTimes; 


Which is accessible in View as,
@for (int i=0; i < ViewBag.NumTimes; i++) {  
    

  • @ViewBag.Message




  • }


    Model is added, using EFCodeFirst,
       << EntityFramework Code First >> for developing model and database.


    Add a class in Model,


    The Classname maps to the Database table and all the public attributes of the class, maps to the database column name.


    Defining the Connection String, for Database connection


         <add name="MovieDBContext" 
          connectionString="Server=.\SQLEXPRESS; 
         Database=Movies;Trusted_Connection=true" 
         providerName="System.Data.SqlClient" />;
    and running the code, generates the database and table according the definition the class.


    Now this, model is accessible from Controller.


    Now using Linq, in the Action method



    1. Query a model,
    2.  Fill the View
    3. Return the view as ActionResult
    4. Now, in the View template ; Model is accessible for displaying. 



    Updating the Model code, like adding a new publics attribute will allow for dropping and re-creating the database again.


    Then using,
        @using (Html.BeginForm()) { 
        @Html.ValidationSummary(true) 


    We can create the form…


    For validation….


    [Required(ErrorMessage = "Title is required")] 
    public string Title { get; set; } 


    So just by few clicks, I have a fully running code auto-generated.

    1 comment:

    1. Its a nice blog posted by you. I was seeking for this type of blog that have a fresh and interesting content.

      ReplyDelete