Using Model Metadata

When we are using Runtime Scaffolding to generate view, We are using @Html.EditorForModel() so here it will populate the model for editing but if we want some fields that should be non editable that we use the model meta data feature, The name space that we need to include is System.Web.Mvc .
Following are some of its attribute that we can use:
  • [HiddenInput] : If we don’t want the property to be editable
  • [HiddenInput(DisplayValue=false)] :  If we don’t want to display the value.

The Fields will be generated in the html but the value will be hidden.  If you are using [ScaffoldColumn(false)] the column will not be generated.

Bellow is the example that explains the usage.
————————————————————————————————————-

 using System;  
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Using_Model_Metadata.Models
{
public class Product
{
[HiddenInput]
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
-------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Using_Model_Metadata.Models;
namespace Using_Model_Metadata.Controllers
{
public class ProductController : Controller
{
//
// GET: /Product/
public ActionResult Index()
{
return View(GetProduct());
}
public Product GetProduct()
{
Product product = new Product { Id = 1, Name = "Kayak", Category = "Watersports", Price = 275m };
return product;
}
}
}
-------------------------------------------------------------------------------------------------------------
@model Using_Model_Metadata.Models.Product
@{
ViewBag.Title = "Index";
}

Index


@Html.EditorForModel()

————————————————————————————————————-
Output

Rendering a Child Action

You can invoke a child action using the Html.Action helper. With this helper, the action method is
executed, the ViewResult is processed, and the output is injected into the response to the client.

Below is the example that explain how you can implement child Action

 using System;  
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace child_Action.Controllers
{
public class ChildActionController : Controller
{
//
// GET: /ChildAction/
public ActionResult Index()
{
return View();
}
public ActionResult ChildActionDemo()
{
return View();
}
[ChildActionOnly]
public ActionResult Time()
{
return PartialView(DateTime.Now);
}
}
}
--------------------------------------------------------------------------------------------------------------
View -> ChildAction->ChildActionDemo
@{
ViewBag.Title = "Child Action Demonstration";
}

This is the method rendered by the action method


@Html.Action("Time")

This is the method rendered by the action method again


--------------------------------------------------------------------------------------------------------------
Partial View: Shared->Time
@model DateTime

The time is: @Model.ToShortTimeString()


Runtime Scaffolding

In this post i will explain what is Runtime Scaffolding.
Runtime Scaffolding means generating the structure of the view at the runtime based on the models. There are three type of Runtime Scaffolding

  • DisplayForModel    Html.DisplayForModel()       Renders a read-only view of the entire model object
  • EditorForModel      Html.EditorForModel()         Renders editor elements for the entire model object
  • LabelForModel      Html.LabelForModel()           Renders an HTML element referring to the  entire model object

Bellow is the example which explains how you can use Runtime Scaffolding

 Create ProductModel  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Test1.Models
{
public class Product
{
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
-------------------------------------------------------------------------------------------------------------
Create Controller RuntimeScaffoldingController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_Grid_Chart.Controllers
{
public class RuntimeScaffoldingController : Controller
{
//
// GET: /RuntimeScaffolding/
public ActionResult RuntimeScaffolding()
{
return View();
}
}
}
-------------------------------------------------------------------------------------------------------------
Create A view
@model Test1.Models.Product
@{
ViewBag.Title = "RuntimeScaffolding";
}

RuntimeScaffolding


@Html.EditorForModel()
----------------------------------------------------------------------------------------------------------
As i have used @Html.EditorForModel() this will desplay the editing option at runtime, In the similar way you can use
Html.DisplayForModel()
Html.LabelForModel()

 Output:

Entity Framework Model First Approach using MVC3

If you don’t yet have a database, you can begin by creating a model using the Entity Framework designer in Visual Studio. When the model is finished, the designer can generate DDL (data definition language) statements to create the database. This approach also uses an .edmx file to store model and mapping information. The What’s New in the Entity Framework 4 tutorial includes a brief example of Model First development.

 Create Models:   
--------------------------------------------------------------------------------------------------------------------
namespace MVCWeb.Models
{
public class Student
{
public int StudentID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ICollection Enrollments { get; set; }
}
}
---------------------------------------------------------------------------------------------------------------
namespace MVCWeb.Models
{
public class Enrollment
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public decimal? Grade { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
}
---------------------------------------------------------------------------------------------------------------
namespace MVCWeb.Models
{
public class Course
{
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public virtual ICollection Enrollments { get; set; }
}
}
--------------------------------------------------------------------------------------------------------------
Create DAL Folder and in that Create 2 Following Files
--------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using MVCWeb.Models;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MVCWeb.DAL
{
public class SchoolContext:DbContext
{
public DbSet Students { get; set; }
public DbSet Enrollments { get; set; }
public DbSet Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove();
}
}
}
-------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using MVCWeb.Models;
namespace MVCWeb.DAL
{
public class SchoolInitializer : DropCreateDatabaseIfModelChanges
{
protected override void Seed(SchoolContext context)
{
var students = new List
{
new Student { FirstMidName = "Carson", LastName = "Alexander", EnrollmentDate = DateTime.Parse("2005-09-01") },
new Student { FirstMidName = "Meredith", LastName = "Alonso", EnrollmentDate = DateTime.Parse("2002-09-01") },
new Student { FirstMidName = "Arturo", LastName = "Anand", EnrollmentDate = DateTime.Parse("2003-09-01") },
new Student { FirstMidName = "Gytis", LastName = "Barzdukas", EnrollmentDate = DateTime.Parse("2002-09-01") },
new Student { FirstMidName = "Yan", LastName = "Li", EnrollmentDate = DateTime.Parse("2002-09-01") },
new Student { FirstMidName = "Peggy", LastName = "Justice", EnrollmentDate = DateTime.Parse("2001-09-01") },
new Student { FirstMidName = "Laura", LastName = "Norman", EnrollmentDate = DateTime.Parse("2003-09-01") },
new Student { FirstMidName = "Nino", LastName = "Olivetto", EnrollmentDate = DateTime.Parse("2005-09-01") }
};
students.ForEach(s => context.Students.Add(s));
context.SaveChanges();
var courses = new List
{
new Course { Title = "Chemistry", Credits = 3, },
new Course { Title = "Microeconomics", Credits = 3, },
new Course { Title = "Macroeconomics", Credits = 3, },
new Course { Title = "Calculus", Credits = 4, },
new Course { Title = "Trigonometry", Credits = 4, },
new Course { Title = "Composition", Credits = 3, },
new Course { Title = "Literature", Credits = 4, }
};
courses.ForEach(s => context.Courses.Add(s));
context.SaveChanges();
var enrollments = new List
{
new Enrollment { StudentID = 1, CourseID = 1, Grade = 1 },
new Enrollment { StudentID = 1, CourseID = 2, Grade = 3 },
new Enrollment { StudentID = 1, CourseID = 3, Grade = 1 },
new Enrollment { StudentID = 2, CourseID = 4, Grade = 2 },
new Enrollment { StudentID = 2, CourseID = 5, Grade = 4 },
new Enrollment { StudentID = 2, CourseID = 6, Grade = 4 },
new Enrollment { StudentID = 3, CourseID = 1 },
new Enrollment { StudentID = 4, CourseID = 1, },
new Enrollment { StudentID = 4, CourseID = 2, Grade = 4 },
new Enrollment { StudentID = 5, CourseID = 3, Grade = 3 },
new Enrollment { StudentID = 6, CourseID = 4 },
new Enrollment { StudentID = 7, CourseID = 5, Grade = 2 },
};
enrollments.ForEach(s => context.Enrollments.Add(s));
context.SaveChanges();
}
}
}
--------------------------------------------------------------------------------------------------------------
In Global.asax add the following on application Start
Database.SetInitializer(new SchoolInitializer());
-------------------------------------------------------------------------------------------------------------
Add Connection String in Web.config

-------------------------------------------------------------------------------------------------------------
Create a controller class, I have created the controller class for student
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCWeb.DAL;
namespace MVCWeb.Controllers
{
public class StudentController : Controller
{
private SchoolContext db = new SchoolContext();
//
// GET: /Student/
public ActionResult Index()
{
return View(db.Students.ToList());
}
}
}
---------------------------------------------------------------------------------------------------------------
Create the Index View for the same
@model IEnumerable
@{
ViewBag.Title = "Index";
}

Index



@Html.ActionLink("Create New", "Create")









@foreach (var item in Model) {






}

LastName

FirstMidName

EnrollmentDate

@Html.ActionLink("Edit", "Edit", new { id=item.StudentID }) |
@Html.ActionLink("Details", "Details", new { id=item.StudentID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.StudentID })

@item.LastName

@item.FirstMidName

@String.Format("{0:g}", item.EnrollmentDate)

run the code and call Student/index it will create the database for you and add the data provided in the SchoolInitializer Class to respective tables.