mvc tutorial for beginners - Part 44 Display and edit templated helpers in asp net mvc

Database, Information Technology mvc tutorial for beginners

496 Lessons

Part 44 Display and edit templated helpers in asp net mvc

Note: Replace ] with GREATERTHAN and [ with LESSTHAN symbol

Templated helpers are introduced in mvc 2. These built in templated helpers can be broadly classified into 2 categories.
1. Display Templates
2. Editor Templates

There are 3 DISPLAY templated helpers
@Html.Display(“EmployeeData”) – Used with a view that is not strongly typed. For example, if you have stored data in ViewData, then

we can use this templated helper using the key that was used to store data in ViewData.
@Html.DisplayFor(model =] model) – Used with strongly typed views. If your model has properties that return complex objects, then

this templated helper is very useful.
@Html.DisplayForModel() – Used with strongly typed views. Walks thru each property, in the model to display the object.

Along the same lines, there are 3 EDIT templated helpers
@Html.EditorFor(model =] model)

To associate metadata with model class properties, we use attributes. In the previous sessions of this video series, we have

discussed about using various data annotations attributes. These templated helpers use metadata associated with the model to

render the user interface.

The built-in display and edit templated helpers can be very easily customised. We will discuss this in a later video session.

We will use the following Employee class that we have been working with in the previous sessions.
public partial class Employee
public class EmployeeMetadata
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }

public string EmailAddress { get; set; }

public int? Salary { get; set; }

public string PersonalWebSite { get; set; }

[DisplayAttribute(Name = “Full Name”)]
public string FullName { get; set; }

[DisplayFormat(DataFormatString = “{0:d}”)]
public DateTime? HireDate { get; set; }

[DisplayFormat(NullDisplayText = “Gender not specified”)]
public string Gender { get; set; }

Copy and paste the following Details action method in HomeController. Notice that, the employee object is stored in ViewData using

“EmployeeData” key.
public ActionResult Details(int id)
SampleDBContext db = new SampleDBContext();
Employee employee = db.Employees.Single(x =] x.Id == id);
ViewData[“EmployeeData”] = employee;
return View();

For the code in Details.cshtml view please refer to my blog using the link above. Since our employee object is in ViewData, we are using @Html.Display(“EmployeeData”) templated helper. At the moment “Details.cshtml” view does not have a Model associated with it. So it is not a strongly typed view.

At this point, if you run the application, you should be able to view Employee details, as expected.

Now, change the implementation of “Details” action method with in home controller as shown below. Notice that, instead of storing

the “Employee” object in ViewData, we are passing it to the View.
public ActionResult Details(int id)
SampleDBContext db = new SampleDBContext();
Employee employee = db.Employees.Single(x =] x.Id == id);
return View(employee);

Change Details.cshtml view using the code from my blog. We have specified “Employee” as the model object. So, here we are working with a strongly typed view, and hence we are using @Html.DisplayFor(model =] model) templated helper. Since, none of the properties of Employee class return a complex object, the ideal choice here would be, to use @Html.DisplayForModel() templated helper. In either cases, in this scenario you will get the same output.

You work with Editor templates in the same way. In HomeController, implement Edit action method as shown below.
public ActionResult Edit(int id)
SampleDBContext db = new SampleDBContext();
Employee employee = db.Employees.Single(x =] x.Id == id);
return View(employee);

and copy the code for Edit.cshtml view from my blog.

Text version of the video


All ASP .NET MVC Text Articles

All ASP .NET MVC Slides

All Dot Net and SQL Server Tutorials in English

All Dot Net and SQL Server Tutorials in Arabic

    _layout _ViewStart .Net .net mvc entity framework @Ajax.ActionLink @RenderSection action action filter actionlink actionname actionresult Adding Advantages ajax ajaxhelper ajaxoptions Alert all checkboxes allowanonymous application areas argument array asp net mvc 5 delete confirmation asp net mvc hyperlink navigation asp net mvc link helper asp net mvc passing list to view asp net mvc required examples asp net mvc update view entity framework asp net mvc url and iis ASP.NET MVC mvc 4 create dropdownlist mvc 4 multi select list mvc 5 crud operations mvc access form collection mvc calendar date picker mvc confirm delete button mvc controller request.querystring mvc controller return string mvc convention over configuration mvc conventions mvc course mvc create hyperlink mvc create new view mvc crud operations mvc crud operations example mvc currency model binder mvc date picker helper mvc datepicker dateformat mvc datepicker example mvc datepicker format mvc datepicker not working mvc datetime datepicker mvc delete confirmation mvc dropdownlist data binding mvc dropdownlist from database mvc dropdownlist required mvc dto viewmodel mvc entity framework mvc example c# mvc example step by step mvc formcollection dropdownlist mvc formcollection empty mvc formcollection example mvc formcollection select mvc get data from database mvc hello world mvc html helper anchor mvc html.actionlink pass parameters mvc htmlhelper extension methods mvc insert to database mvc insert update delete mvc javascript confirm delete mvc jquery datepicker editorfor mvc jquery datepicker example mvc list view example mvc make dropdownlist required mvc model object mvc model validation mvc model validation example mvc multiple tables mvc pass model to view mvc razor foreach loop mvc required attribute mvc required field mvc required field validation mvc selectlist from database mvc tutorial mvc two tables mvc url mapping mvc version mvc view example mvc view foreach example mvc view from controller mvc view function mvc view validation mvc viewmodel example mvc viewmodel tutorial aspx assembly attack attribute Attributes Authorize auto auto generated autocomplete automatic avoid bad bellevue benefits between bi-directional bidirectional bind attribute bind mvc dropdownlist with database values black list brail built business objects C# c# mvc checkboxfor default checked c# mvc crud example c# mvc crud tutorial c# mvc entity framework tutorial c# mvc get checkbox value c# mvc object reference not set to an instance of an object cacheprofiles CDN CHECK checkbox checkbox list checkboxlist checking child actions childactiononly classes Client client-side code code blocks comments compare compareattribute compile time complete complex compress compression constant content control controller controller action controllers Convention create create mvc application create view Creating cross site scripting CRUD crud operations in mvc 5 crud operations in mvc 5 using entity framework currency format in mvc 4 current() custom custom errors custom view engine customize customizing Data data access Data Annotations data transfer object data- attributes database datatransferobject DataTypeAttribute date format in c# mvc date format in mvc razor date in mvc view datetime datetime in mvc model datetime picker delete Deleting delivery demo Detect determine diference difference differences disable disabled disadvantages display display data from two tables in mvc DisplayAttribute DisplayColumnAttribute DisplayFormatAttribute displaying data from multiple tables in mvc down download dropdownlist DropDownListFor dynamic views edit edit view editing edits employee department mvc enable encode encoding entity framework entity framework mvc entity framework mvc tutorial entity framework in mvc entity framework in mvc 4 entity framework in mvc tutorial errors escape example example of mvc with text box in c# exclude excluding explained explicit code nugget expression fallback feedback fiddler mvc post Fields files filters FIND find out first for beginners foreach in mvc razor view form format date in mvc controller FormCollection from functionality generate generating get request handleerror HandleErrorAttribute helpers hiddeninput HiddenInputAttribute how mvc works how does mvc know which view to return how iis process mvc request how mvc request is processed how to create mvc application in visual studio 2013 how to install mvc 3 how to install mvc 4 how to install mvc 4 in visual studio 2010 how-to html html helper html helper for textbox html helpers html.dropdownlist Html.DropDownListFor Html.Partial Html.RadioButton Html.RadioButtonFor Html.RenderPartial Html.TextBox Html.TextBoxFor HtmlHelper httpget httppost hyperlinks image images implement implementing include including index view insert install install mvc 3 installing mvc 3 installing mvc 4 interfaces is IsSectionDefined IsValid item javascript jquery jquery datepicker example in mvc key value pair keys layout links List Box listbox literal text loaded LoadingElementDuration LoadingElementI local locate location make a field required mvc method method mvc methods min.js Minification minified minify Model model binding model binding in mvc model metadata Model–view–controller models multiple multiple tables MVC mvc @model in view mvc 3 mvc 4 mvc 4 edit controller example mvc 4 edit view mvc 4 pass list from view to controller mvc access model in view mvc add validation dynamically mvc application mvc bind view to model mvc c# crud mvc checkboxfor checked by default mvc checkboxfor database mvc checkboxfor default value mvc checkboxfor get value mvc checkboxlist from database mvc combobox database selected value mvc combobox selected value mvc controller mvc create textbox mvc database example c# mvc dropdownlist database example mvc dropdownlist entity framework mvc dropdownlist entity framework database first mvc dropdownlist required validation mvc dropdownlist viewbag example mvc edit controller example mvc edit form example mvc edit httppost mvc edit page example mvc edit view drop down list mvc edit view example mvc editable drop down list mvc email hyperlink mvc employee example mvc entity framework c# tutorial mvc entity framework example mvc formcollection example mvc get all checked checkboxes mvc get selected items listbox mvc hide field in view mvc hide model property mvc htmlhelper best practices mvc htmlhelper hidden field mvc htmlhelper strongly typed mvc layout mvc listbox get selected items in controller mvc loop through checkboxes mvc mailto link mvc model mvc model attributes email mvc model class example mvc model example c# mvc model validation example mvc multiselect listbox mvc pages mvc partial class metadata mvc radio button database mvc radio button selected value mvc radiobuttonfor checked mvc razor edit form mvc razor edit view mvc razor html.dropdownlist example mvc razor mailto link mvc required attribute example mvc retrieve data from database mvc return view viewname mvc uihint example mvc update database from model mvc update example mvc update stored procedure mvc view search locations mvc2 mvc3 mvc3 html.actionlink parameters mvc4 Named sections navigation network new row nonaction not working Obtrusive OnBegin OnComplete OnFailure OnSuccess open in a new browser window Operations outputcache outputcacheattribute override own page pager pagination paging parameter types partial partial views partialviews pass model from controller to view mvc 4 pass model to view from controller pass viewmodel to controller c# populating post post request posted form values precompiling prevent preventing prevention progress project properties Public purpose RadioButtonFor radiobuttonlist range rangeattribute razor razor edit view dropdown razor multi select listbox read readonly ReadOnlyAttribute records Reflection regularexpression regularexpressionattribute remote RemoteAttribute render rendered RenderPartial request data requirehttps requirehttpsattribute restrict access result Routing rows runtime ScaffoldColumnAttribute Screen search search capability section sections select selected selected value selectedvalue selectlist selectlistitem selectors Server show side simple single sort Sorting Spark stringlength strongly typed html helpers strongly typed html helpers mvc 4 strongly typed views Structure summary support Syntax t4 templates templated helpers Templates text tag TextBox TextBoxFor the view index or its master was not found mvc 4 tryupdatemodel tutorial typeof uihint uihint attribute mvc uncheck Unintended updates Unobtrusive Update update view mvc updatemodel updating url Use use of using using fiddler with mvc using foreach in razor view validateinput validateinputattribute validation validation mvc validationsummary value values versions vewbag view view engines view index or its master was not found viewbag pass data from controller to view viewdata viewdata viewbag viewmodel ViewData.ModelMetadata ViewData.TemplateInfo viewmodel views viewstart visual visual studio create mvc application visual studio create mvc project what what is the use of shared folder in mvc white list Why Working working with multiple tables in mvc using entity framework xss