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

Published by Nirbhay

Technology Geek,Blogger,Reviewer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: