18 April 2014

Accessing Models Data from Controller -- MVC Basics

The below given example shows how to access Models Data from Controller. 

Create new project, add Context class 'NewDatabase.cs' and Model class 'Country.cs'

NewDatabase.cs

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Data.Entity;
Namespace MvcApplication2.Models
{
    Public class NewDatabase:DbContext
    {
        Public DbSet<country>Country { get; set; }      
    }
}

Country.cs

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.ComponentModel.DataAnnotations;
Namespace MvcApplication2.Models
{
    Public class Country
    {
        [Key]
        Public virtual int country_id {get; set ;}
        [Required]
        Public virtual string country name {get; set ;}
    }
}


Add a Controller 'CountryController'

Country Controller.cs

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.Mvc;
Using MvcApplication2.Models; 
Namespace MvcApplication2.Controllers
{
    Public class Country Controller: Controller
    {
        //
        // GET: /Country/
        NewDatabase db = new NewDatabase ();
        Public ActionResult Index ()
        {   
            //Shows Country details
            Var model = db.Country;
            Return View (model);
        } 
        Public ActionResult AddCountry ()
        { 
            Return View ();
        }
        [Http Post]
        Public ActionResult AddCountry (Country model)
        {
           
            // Attempt to add the country name
            db.Country.Add (model);
            db.SaveChanges ();  
            Return View (model);
        } 
    }
}

Run the Project
 



 





 

No comments:

Post a Comment