Friday, May 18, 2012

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";  
 }  
 <h2>Index</h2>  
 @Html.EditorForModel()  
-------------------------------------------------------------------------------------------------------------
Output

No comments:

Post a Comment