• Home

Logo

Navigation
  • Home
  • Articles
    • Content Writing
    • Design
    • General
    • Internet Marketing
    • Social Media
    • Tools and Tips
    • Usability
    • Web Hosting Articles
  • Tutorials
    • AJAX Tutorials
    • ASP Tutorials
    • C# Tutorials
    • CGI and Perl Tutorials
    • CSS Tutorials
    • Flash Tutorials
    • HTML Tutorials
    • Illustrator Tutorials
    • Java Tutorials
    • JavaScript Tutorials
    • Linux Tutorials
    • Miscellaneous Tutorials
    • MySQL Tutorials
    • Photoshop Tutorials
    • PHP Tutorials
    • Python Tutorials
    • Wireless Tutorials
    • WordPress Tutorials
    • XML Tutorials
  • Scripts
    • AJAX Scripts
    • ASP Scripts
    • ASP.NET Scripts
    • CGI & Perl Scripts
    • Flash Scripts
    • Java Scripts
    • JavaScript Scripts
    • PHP Scripts
    • Python Scripts
    • Remotely Hosted
    • Tools and Utilities
    • XML Scripts
  • Answers
  • Online Services
  • Tools

Rolling with Razor in MVC v3 Preview – Part 3

By Larry Schoeneman | on Aug 12, 2010 | 0 Comment
ASP Tutorials
  • Tweet
  • Share
  • Tweet
  • Share

When last we met…

In the last installment, we took a look at Layout pages and their relation to views. We also examined the use of sections and the RenderSection method. In this installment we are going to look at partial views and their place in the Razor view engine.

Taking a look at partial views

Partial views are currently the closest thing the Razor view engine has to “user” controls from the traditional asp.net non-MVC world. Partial views have their own view data so they can be reused independently of their containing view. This allows us to build reusable components, although not typically at the complexity level found in asp.net controls. Then again, we don’t have to carry around view state or any other postback related baggage either. There is always a tradeoff.

In our containing view, if we want to use a partial view, we will need to indicate this by using:

   @Html.Partial(“_MyPartial”);

This will “include” or use the _MyPartial partial view, passing in no additional view data. Additionally, we can use the following format to include view data:

   @Html.Partial(“_MyPartial”, ViewData);

Where ViewData is the ViewModel we want to pass in, just like we normally do in a call to View in our controller. Incidentally, it is perfectly okay to call a partial from the View method in your controller. It will treat it as a full blown view.

To create a simple, partial view, first we need to figure out where to put it. If you plan on it being used by multiple views activated by multiple controllers, I would recommend placing it in the Views\Shared directory. If that is not the case, place it in the appropriate view subdirectory (such as Home).

Let’s create a sample partial view using the default razor project. As explained in part one of this series, please create a standard project using the asp.net mvc 3 wizard using Razor. Now, to create our partial view, right click on the shared folder and select Add->View. One thing to note in the dialog is that we can choose to use razor (cshtml) or aspx! You read that correctly, boys and girls, we can mix and match view engines at will with no adverse effects, other than some developer confusion. But that is a small price to pay for flexibility. Anyway, when you select Add, The following dialog will appear:

The naming convention for the View name appears to be _Name for partial views. At least that’s what I’ve seen from Scott Guthrie (pretty much the God of all things asp.net mvc) So, change the view name to be something like “_MyPartial” and check the box next to “Create a partial view.” For this example, we will not check “Create a strongly typed view.” Also, make sure the view engine is set to Razor. Be sure not to add a reference to the master page in your partial view. If you use the partial view in your master page and it calls the partial view, which references the master page, which calls the….you get the point.

After all that, a cshtml file will be created which looks like:

   @inherits System.Web.Mvc.WebViewPage<dynamic>

From here you use any of the razor abilities we’ve already discussed as well as any html. Additionally, the ViewModel dictionary is available here, using the .Net 4.0 framework’s new dynamic keyword.

So in the main view, you could write:

   @{ View.Message = “My Message”; }

This is different than assigning it in the controller, where it is called ViewModel. Then in the partial view, we could reference this as:

   @View.Message

This will display My Message. Note that you need to use @{ View.Message = “My Message”; } otherwise it will display =My Message which isn’t what we want.

We can also use a strongly typed class as our view model. For this example, we have created the following class:

public class Person
{
public string Name{ get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}

Now, once again, right click on shared and select Add, View. This time, create a strongly typed view, and select the person type from the drop down. You can also select a template to use to view the content. The available ones are Create, Delete, Details, Edit and List. This enables you to build basic CRUD (Create, Update, Delete) functionality really quickly. For this example, we will select the Create Template. The Add View window should look like:

This creates the following code as a partial view:

@inherits System.Web.Mvc.WebViewPage<MvcApplication1.Models.Person>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
<legend>Fields</legend>
<div class=”editor-label”>
   @Html.LabelFor(model => model.Name)
</div>
<div class=”editor-field”>
   @Html.TextBoxFor(model => model.Name)
   @Html.ValidationMessageFor(model => model.Name)
</div>

<div class=”editor-label”>
   @Html.LabelFor(model => model.Address)
</div>
<div class=”editor-field”>
   @Html.TextBoxFor(model => model.Address)
   @Html.ValidationMessageFor(model => model.Address)
</div>

<div class=”editor-label”>
   @Html.LabelFor(model => model.City)
</div>
<div class=”editor-field”>
   @Html.TextBoxFor(model => model.City)
   @Html.ValidationMessageFor(model => model.City)
</div>
<div class=”editor-label”>
   @Html.LabelFor(model => model.State)
</div>
<div class=”editor-field”>
   @Html.TextBoxFor(model => model.State)
   @Html.ValidationMessageFor(model => model.State)
</div>
<div class=”editor-label”>
   @Html.LabelFor(model => model.Zip)
</div>
<div class=”editor-field”>
   @Html.TextBoxFor(model => model.Zip)
   @Html.ValidationMessageFor(model => model.Zip)
</div>
<p>
<input type=”submit” value=”Create” />
</p>
</fieldset>
}
<div>
   @Html.ActionLink(“Back to List”, “Index”)
</div>

That is a lot of code for a single click!

Now, just by using it in our controller, i.e.

   return View(“_PersonDetails”, new Person{…});

We can use it as our view and it will fill in the fields with the values we provided when we created our person object.

We can also use it as part of a bigger page, as the term partial view implies. For example, to include it in a page containing other information and this screen, all we need to do is:

   @inherits System.Web.Mvc.WebViewPage<MvcApplication1.Models.Person>

   @{
   View.Title = “Home Page”;
   LayoutPage = “~/Views/Shared/_Layout.cshtml”;

   }

Below, we have an embedded partial view
<p>

   @Html.Partial(“_PersonDetails”, ViewData)
</p>

A couple of items are worth noting. First, in this case, I am explicitly passing in the ViewData. This is NOT required, and you can omit it if you just want to use the view data passed to the view. i.e. @Html.Partial(“_PersonDetails”). However, you can also send different data. For example, if your partial view only took one string instead of an object, you could use

   @Html.Partial(“_PersonDetails”, ViewData.Model.Name)

Or any other string for that matter. One thing to keep in mind is that @Html.Partial doesn’t seem to play particularly nice with dynamic yet, so ViewData is the way to go for now. This may change in the future though.

Summary

In this installment, we’ve reviewed partial views and all the fun stuff that comes with it. There are some interesting quirks, some of which are razor, some of which are mvc 3. In the next installment, we’ll look at control structures and start to wrap up this introduction.

Share this story:
  • tweet

Author Description

Larry Schoeneman is a software developer with over 20 years of experience, focused on Microsoft products and technologies as well as utilizing agile methodologies to build better software.

No Responses to “Rolling with Razor in MVC v3 Preview – Part 3”

You must be logged in to post a comment.

Connect With Us

RSSSubscribe 1,242Followers 494Likes
  • Popular
  • Recent
  • Comments
  • Creating Energy Spheres in Photoshop

    Apr 15, 2008 - 96 Comments
  • Easy Screen Scraping in PHP with the Simple HTML DOM Library

    Aug 6, 2008 - 20 Comments
  • Calculating date difference more precisely in PHP

    Mar 7, 2008 - 13 Comments
  • When Does Hosting Your Website in the Cloud Make Sense?

    Oct 8, 2010 - 2 Comments
  • Fun with the Microsoft Managed Extensibility Framework Part 2

    Oct 6, 2010 - 0 Comment
  • Fun with the Microsoft Managed Extensibility Framework Part 1

    Sep 22, 2010 - 0 Comment
  • Website Management on the go with the iPad

    I appreciated your post, but I was looking for something I didn't...
    November 24, 2012 - drmoderator
  • Creating Energy Spheres in Photoshop

    I'm a little stuck down here especially at the step of creating the...
    November 23, 2012 - sarah
  • Running background processes in PHP

    Can you give an example? As see it, you can use this only when you...
    November 16, 2012 - Shaked Klein Orbach
Developer Resources
  • Tutorial Directory
  • Learn HTML
  • Learn PHP
  • Learn CSS
  • Learn AJAX
  • Learn JavaScript
  • Learn Pear
  • White Papers
  • Resources
    • NetVisits Web Directory
    • Realtor Pixels
    • Answers On The Run
    • Ask A Geek
  • Recent Posts

    • When Does Hosting Your Website in the Cloud Make Sense?
    • Fun with the Microsoft Managed Extensibility Framework Part 2
    • Fun with the Microsoft Managed Extensibility Framework Part 1
    • Website Management on the go with the iPad
    • Code Contracts in C# 4.0 – Part 1

    Calendar

    May 2013
    M T W T F S S
    « Oct    
     12345
    6789101112
    13141516171819
    20212223242526
    2728293031  

    Recent Comments

    • drmoderator on Website Management on the go with the iPad
    • sarah on Creating Energy Spheres in Photoshop
    • Shaked Klein Orbach on Running background processes in PHP
    • Thomas Cuvillier on How To Upload Files Using PHP
    • rizal aditya on Extracting text from Word Documents via PHP and COM
    • Home
    © 2003 - 2013 DeveloperTutorials.com. All Rights Reserved. Privacy Policy.