SlideShare a Scribd company logo
Instant Ebook Access, One Click Away – Begin at ebookgate.com
ASP NET MVC in Action 1st Edition Jeffrey Palermo
https://ebookgate.com/product/asp-net-mvc-in-action-1st-
edition-jeffrey-palermo/
OR CLICK BUTTON
DOWLOAD EBOOK
Get Instant Ebook Downloads – Browse at https://ebookgate.com
Click here to visit ebookgate.com and download ebook now
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...
ASP NET MVC 2 in Action 2nd Edition Jeffrey Palermo
https://ebookgate.com/product/asp-net-mvc-2-in-action-2nd-edition-
jeffrey-palermo/
ebookgate.com
Professional ASP NET MVC 2 1st Edition Jon Galloway
https://ebookgate.com/product/professional-asp-net-mvc-2-1st-edition-
jon-galloway/
ebookgate.com
Test Drive ASP NET MVC 1st Edition Jonathan Mccracken
https://ebookgate.com/product/test-drive-asp-net-mvc-1st-edition-
jonathan-mccracken/
ebookgate.com
Professional ASP NET MVC 1 0 1st Edition Rob Conery
https://ebookgate.com/product/professional-asp-net-mvc-1-0-1st-
edition-rob-conery/
ebookgate.com
What s New in ASP NET MVC 2 1st Edition Simone Chiaretta
https://ebookgate.com/product/what-s-new-in-asp-net-mvc-2-1st-edition-
simone-chiaretta/
ebookgate.com
Pro ASP NET MVC 3 Framework 3rd Edition Steven Sanderson
https://ebookgate.com/product/pro-asp-net-mvc-3-framework-3rd-edition-
steven-sanderson/
ebookgate.com
Bootstrap for ASP NET MVC Second Edition Pieter Van Der
Westhuizen
https://ebookgate.com/product/bootstrap-for-asp-net-mvc-second-
edition-pieter-van-der-westhuizen/
ebookgate.com
Expert ASP NET Web API 2 for MVC developers 1st Edition
Adam Freeman
https://ebookgate.com/product/expert-asp-net-web-api-2-for-mvc-
developers-1st-edition-adam-freeman/
ebookgate.com
Pro ASP NET Web API HTTP Web Services in ASP NET 1st
Edition Tugberk Ugurlu
https://ebookgate.com/product/pro-asp-net-web-api-http-web-services-
in-asp-net-1st-edition-tugberk-ugurlu/
ebookgate.com
ASP NET MVC in Action 1st Edition Jeffrey Palermo
M A N N I N G
Jeffrey Palermo
Ben Scheirman
Jimmy Bogard
FOREWORD BY PHIL HAACK
IN ACTION
ASP.NET MVC in Action
ASP NET MVC in Action 1st Edition Jeffrey Palermo
ASP.NET MVC
in Action
WITH MVCCONTRIB, NHIBERNATE, AND MORE
JEFFREY PALERMO
BEN SCHEIRMAN
JIMMY BOGARD
M A N N I N G
Greenwich
(74° w. long.)
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
Sound View Court 3B fax: (609) 877-8256
Greenwich, CT 06830 email: orders@manning.com
©2010 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in
any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books are
printed on paper that is at least 15% recycled and processed without the use of elemental chlorine.
Development Editor: Tom Cirtin
Copyeditor: Betsey Henkels
Manning Publications Co. Proofreader: Elizabeth Martin
Sound View Court 3B Typesetter: Gordan Salinovic
Greenwich, CT 06830 Cover designer: Leslie Haimes
ISBN 978-1-933988-62-7
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – MAL – 14 13 12 11 10 09
v
brief contents
1 ■ Getting started with the ASP.NET MVC Framework 1
2 ■ The model in depth 24
3 ■ The controller in depth 44
4 ■ The view in depth 65
5 ■ Routing 91
6 ■ Customizing and extending the ASP.NET MVC Framework 119
7 ■ Scaling the architecture for complex sites 152
8 ■ Leveraging existing ASP.NET features 174
9 ■ AJAX in ASP.NET MVC 195
10 ■ Hosting and deployment 216
11 ■ Exploring MonoRail and Ruby on Rails 238
12 ■ Best practices 270
13 ■ Recipes 312
ASP NET MVC in Action 1st Edition Jeffrey Palermo
vii
contents
foreword xiii
preface xv
acknowledgments xviii
about this book xxi
about the authors xxvi
about the cover illustration xxviii
1 Getting started with the ASP.NET MVC Framework 1
1.1 Picking apart the default application 3
Creating the project 4 ■
Your first routes 7 ■
Running with the
starter project 9
1.2 Your first ASP.NET MVC controller from scratch 14
1.3 Our first view 16
1.4 Ensuring the application is maintainable 18
1.5 Testing controller classes 20
1.6 Summary 22
2 The model in depth 24
2.1 Understanding the basics of domain-driven design 25
2.2 Domain model for this book 26
Key entities and value objects 26 ■
Aggregates 27 ■
Persistence
for the domain model 29
CONTENTS
viii
2.3 Presentation model 31
Presentation model responsibilities 31 ■
Projecting from the
domain model 33
2.4 Working with the model 34
Crafting the route 35 ■
Crafting the controller action 35 ■
Test-
driving the feature 36 ■
Finishing the view 39
2.5 Summary 42
3 The controller in depth 44
3.1 The controller action 45
3.2 Simple controllers do not need a view 47
3.3 Testing controllers 50
Testing the RedirectController 50 ■
Making dependencies
explicit 52 ■
Using test doubles, such as stubs and
mocks 53 ■
Elements of a good controller unit test 55
3.4 Simple actions and views 56
3.5 Working with form values 57
3.6 Processing querystring parameters 58
3.7 Binding more complex objects in action parameters 59
3.8 Options for passing ViewData 61
3.9 Filters 62
3.10 Summary 64
4 The view in depth 65
4.1 How ASP.NET MVC views differ from Web Forms 66
4.2 Folder structure and view basics 67
4.3 Overview of view basics 69
Examining the IViewEngine abstraction 70 ■
Understanding
master pages in the ASP.NET MVC Framework 71 ■
Using
ViewData to send objects to a view 73 ■
Partial views can help
decompose a complex screen 76
4.4 Leveraging the view to create dynamic screens 79
Rendering forms with view helpers and data binding 79 ■
Posting
HTML forms back to the server 84 ■
Validation and error
reporting 85 ■
Extending HtmlHelper 88
4.5 Summary 90
CONTENTS ix
5 Routing 91
5.1 What are routes? 92
What’s that curl command? 92 ■
Taking back control of the URL
with routing 94
5.2 Designing a URL schema 95
Make simple, clean URLs 95 ■
Make hackable
URLs 96 ■
Allow URL parameters to clash 96 ■
Keep URLs
short 97 ■
Avoid exposing database IDs wherever possible 97
Consider adding unnecessary information 98
5.3 Implementing routes in ASP.NET MVC 99
URL schema for an online store 102 ■
Adding a custom static
route 103 ■
Adding a custom dynamic route 103 ■
Catch-all
routes 105
5.4 Using the routing system to generate URLs 107
5.5 Creating routes for Code Camp Server 108
5.6 Testing route behavior 111
5.7 Using routing with existing ASP.NET projects 115
5.8 Summary 117
6 Customizing and extending the ASP.NET MVC Framework 119
6.1 Extending URL routing 120
6.2 Creating your own ControllerFactory 125
The ControllerFactory implementation 126 ■
Leveraging IoC for
your controllers 130
6.3 Extending the controller 134
Creating a FormattableController 135 ■
Working with action
filters 138
6.4 Creating a custom view engine 141
6.5 Customizing Visual Studio for ASP.NET MVC 145
Creating custom T4 templates 145 ■
Adding a custom test project
template to the new project wizard 148
6.6 Summary 150
7 Scaling the architecture for complex sites 152
7.1 Taming large controller actions 153
7.2 Whipping views into shape 156
Using and creating view helpers 156 ■
Creating
partials 159 ■
Creating components 163
CONTENTS
x
7.3 Using action filters to load common data 165
7.4 Organizing controllers into areas 167
Capturing the area for a request 168 ■
Creating a view engine
with support for areas 168 ■
Tying it all together 171
7.5 Summary 172
8 Leveraging existing ASP.NET features 174
8.1 ASP.NET server controls 175
The TextBox 175 ■
Other common controls 176 ■
The
GridView 178 ■
Where do I get the good stuff? 179
8.2 State management 179
Caching 179 ■
Session state 183 ■
Cookies 184 ■
Request
storage 184
8.3 Tracing and debugging 185
TraceContext 186 ■
Health monitoring 186
8.4 Implementing personalization and localization 187
Leveraging ASP.NET personalization 187 ■
Leveraging
ASP.NET localization 188
8.5 Implementing ASP.NET site maps 192
8.6 Summary 194
9 AJAX in ASP.NET MVC 195
9.1 Diving into AJAX with an example 196
9.2 AJAX with ASP.NET Web Forms 198
9.3 AJAX in ASP.NET MVC 200
Hijaxing Code Camp Server 201 ■
AJAX with JSON 207
Adding alternate view formats to the controller 208 ■
Consuming
a JSON action from the view 210 ■
AJAX helpers 213
9.4 Summary 214
10 Hosting and deployment 216
10.1 Deployment scenarios 217
10.2 XCOPY deployment 218
10.3 Deploying to IIS 7 219
10.4 Deploying to IIS 6 and earlier 223
Configuring routes to use the .aspx extension 224 ■
Configuring
routes to use a custom extension 225 ■
Using wildcard mapping
with selective disabling 226 ■
Using URL rewriting 229
CONTENTS xi
10.5 Automating deployments 232
Employing continuous integration 232 ■
Enabling push-button XCOPY
deployments 233 ■
Managing environment configurations 234
10.6 Summary 237
11 Exploring MonoRail and Ruby on Rails 238
11.1 MonoRail 239
Feature overview 239 ■
ActiveRecord and Windsor 248
MonoRail and Castle features available in ASP.NET MVC 255
11.2 Ruby on Rails 255
Convention over configuration and “the Rails way” 256 ■
Active
Record 260 ■
ActionPack 264
11.3 Summary 269
12 Best practices 270
12.1 Controllers 271
Layer Supertype 271 ■
Filters 272 ■
Smart binders 274
Hardcoded strings 279 ■
Separated view models 280
Validation 281
12.2 Views 283
Strongly typed views 283 ■
Fighting duplication 284 ■
Embracing
expressions 286
12.3 Routes 289
Testing routes 289 ■
Action naming 292
12.4 Testing 294
Controller unit tests 295 ■
Model binder unit tests 298 ■
Action filter
unit tests 301 ■
Testing the last mile with UI tests 303
12.5 Summary 311
13 Recipes 312
13.1 jQuery autocomplete text box 312
13.2 Automatic client-side validation 318
13.3 Data access with NHibernate 325
Functional overview of reference implementation 326
Application architecture overview 327 ■
Domain model—the
application core 328 ■
NHibernate configuration—infrastructure
of the application 330 ■
UI leverages domain model 338
Pulling it together 341 ■
Wrapping up data access with
NHibernate 344
CONTENTS
xii
13.4 Designing views with the Spark view engine 345
Installing and configuring Spark 345 ■
Simple Spark view
example 347
13.5 Summary 351
index 353
xiii
foreword
The final version of ASP.NET MVC 1.0 was released March 2009 during the Mix 09 con-
ference and nobody was caught by surprise with what was inside—and this is a good
thing. Before the debut of the final version, the product team had released multiple
public previews with full source code in an effort to raise the bar on openness and
community involvement for a Microsoft product.
Why would we do this?
Transparency and community involvement are noble goals, but they aren’t neces-
sarily the end goal of a project. What we’re really after is great product. I like to think
of ASP.NET MVC as almost an experiment to demonstrate that transparency and com-
munity involvement were great means to achieving that goal.
After Preview 2 of ASP.NET MVC was released, we received a lot of feedback from
developers that writing unit tests with ASP.NET MVC was difficult. Jeffrey Palermo, the
lead author of ASP.NET MVC in Action, was among the most vocal in providing feedback
during this time. We took this feedback and implemented a major API change by
introducing the concept of action results, which was a much better design than we
had before. Community involvement helped us build a better product.
ASP.NET MVC focuses on solid principles such as separation of concerns to provide
a framework that is extremely extensible and testable. While it’s possible to change the
source as you see fit, the framework is intended to be open for extension without need-
ing to change the source. Any part of the framework can be swapped with something
else of your choosing. Don’t like the view engine? Try Spark view engine. Don’t like the
way we instantiate controllers? Hook in your own dependency injection container.
FOREWORD
xiv
ASP.NET MVC also includes great tooling such as the Add View dialog, which uses
code generation to quickly create a view based on a model object. The best part is that
all the code generation features in ASP.NET MVC rely on T4 templates and are thus
completely customizable.
With this book, Jeffrey will share all these features and more, as well as show how to
put them together to build a great application. I hope you enjoy the book and share
in his passion for building web applications. Keep in mind that this book is not only
an invitation to learn about ASP.NET MVC, but also an invitation to join in the commu-
nity and influence the future of ASP.NET MVC. Happy coding!
PHIL HAACK
SENIOR PROGRAM MANAGER
ASP.NET MVC TEAM
MICROSOFT
xv
preface
My career started in the mid-nineties as one of the early web developers. Web as in
HTTP, that is. Netscape Navigator was helping to grow the number of households with
internet modems because it was more advanced than anything else at the time.
Netscape Navigator 3.0 (1996) and 3.04 (1997) helped households and businesses all
over the world open up the internet for common uses. There is no more common a
task than shopping! With the advent of ecommerce, the internet exploded with a cap-
italist gold run.
I started web development in the public sector where we leveraged the first threads
of social networking by allowing school district graduates to collaborate with former
classmates. I started my career on the Microsoft platform using IDC (Internet Database
Connector) with HTX (HTML Extension Template). Internet Information Services (IIS) 2.0
gave us fantastic flexibility using ODBC data sources. This was my first use of the “code
nugget,” or <% %> delimiters. IDC/HTX gave way to Active Server Pages (ASP), and I
can still recall following the changes as they broke–ASP 2.0 to ASP 3.0 as well as the awe-
some COM+ integration. I dabbled in CGI, Perl, Java, and C++, but stayed with the
Microsoft platform. Observing the Visual Basic explosion from the sidelines, I learned
the ropes with small utility apps.
Active Server Pages 3.0 saw the browser wars with Internet Explorer 4, released
with Windows 95, competing with Netscape for market share. Writing web applica-
tions that worked well with both browsers was difficult. IE 5.0 opened the horizons for
intranet applications with proprietary web extensions like the XML data island and
better scripting capabilities. Windows XP shipped with IE 6, which effortlessly cap-
tured the majority of the web browser market. ASP 3.0 put the programmer intimately
PREFACE
xvi
in touch with HTTP, HTML, and the GET and POST verbs. I remember pulling out
crude frameworks to handle multiple request paths from the same ASP script.
At the same time ASP 3.0 was enjoying widespread adoption, Struts was taking the
Java web application world by storm. Struts is probably the best known Java MVC frame-
work, although today there are many popular frameworks for the JVM. With ASP 3.0, I
was unaware of the lessons my Java counterparts had already learned, although I felt the
pain of myriad responsibilities lumped into a single ASP script.
I adopted ASP.NET 1.0 right out of the gate and converted some of my ASP 3.0 sites
to Web Forms. Remember when GridLayout was the default with CSS absolute posi-
tioning everywhere? It was clear that Web Forms 1.0 was geared for VB6 developers
coming over to .NET and getting onto the web. The post-backs and button click han-
dlers were largely foreign to me, but my colleagues who were seasoned VB6ers felt
right at home. ASP.NET 1.1 dropped the GridLayout and forced the developer to
understand HTML and how flow layout works. Down-level rendering was great when
Internet Explorer was the “preferred” browser, and everything else was downlevel. That
paradigm started to break down as Firefox climbed in market share and demanded
standards-compliant markup.
I became an ASP.NET expert and was a frequent blogger during the .NET 2.0 beta
cycle. I knew every feature and every breaking change from ASP.NET 1.1 to 2.0, and
helped my team adopt 2.0. During the ASP.NET 2.0 era, I started following Martin
Fowler and his Model-View-Presenter writings. I implemented that pattern to pull away
logic from the code-behind file, which had become bloated. Java developers, in 2005,
were enjoying a choice of several MVC frameworks for the web. I, on the other hand, was
wrestling Web Forms into Model-View-Presenter and test-driven development submis-
sion. It was exhausting, but what was the alternative?
In 2006, with a job change, I jumped over to software management and smart client
development with WinForms. With the familiar clunkiness of the code-behind model,
and a development team to manage, I implemented the Model-View-Controller pattern
with the WinForm class as the view. It was a breath of fresh air. UI development was
seamless, and the controllers were a natural boundary from the domain model to the
UI. In 2007, I jumped back into web development and begrudgingly implemented
Model-View-Presenter with Web Forms again. In retrospect, I wish I had adopted Mono-
Rail, another Model-View-Controller framework for .NET.
In February 2007, Scott Guthrie (ScottGu) created a prototype of what would
become the ASP.NET MVC framework. He had heard from many customers about the
difficulties with Web Forms and how they needed a simpler, more flexible way to write
web applications. At the 2007 MVP Summit, Scott sought input from a small group of
Microsoft MVPs. Darrell Norton, Scott Bellware, Jeremy Miller, and I validated the vision
of his prototype and gave initial input that would end up coded into the framework.
When Scott Guthrie presented, to an audience in Austin, Texas, a working proto-
type and vision for ASP.NET MVC at the AltNetConf open spaces conference in Octo-
ber 2007, I knew instantly that this is what I’d wished for all along. As a long-time web
developer, I understood HTTP and HTML, and this, I believe, is what ASP.NET 1.0
should have been. It would have been such a smooth transition from ASP 3.0 to
PREFACE xvii
ASP.NET MVC. I can claim the first ASP.NET MVC application in production because I
convinced Scott to give me a copy of his prototype and revised my www.partywithpal-
ermo.com registration site, launching it in November 2007 on one of Rod Paddock’s
servers at DashPoint.
What Microsoft did with the ASP.NET MVC release cycle was an unprecedented
project in the Developer Division. The project was released at least quarterly on the
CodePlex site, source code and all. It was also developed using test-driven develop-
ment as the software construction technique. Full unit test coverage is included in the
source code download, and ASP.NET MVC 1.0 was released under the MS-PL, and OSI-
approved open source license.
ASP.NET MVC works the way the web works; it’s a natural fit. Although Microsoft is
last to the table with a Model-View-Controller framework for its development plat-
form, this framework is a strong player. Its design focuses on the core abstractions
first. It is conducive to extension by the community. In fact, the same week the first
Community Technology Preview (CTP) was released, Eric Hexter and I launched the
MvcContrib open-source project with an initial offering of extensions that integrated
with the ASP.NET MVC Framework.
At the time of publishing this book, the ASP.NET MVC framework is a frequently
used tool at Headspring Systems, where I facilitate the consulting practice. For the
.NET industry as a whole, I predict that ASP.NET MVC will be considered the norm for
ASP.NET development by 2011.
New developers are coming to the .NET platform every day, and for web develop-
ers, ASP.NET MVC is easy to adopt and learn. Because of the decreased complexity, the
barrier to adoption is lowered, and because of the simplicity, it can grow to meet the
demands of some of the most complex enterprise systems.
When Manning Publications approached me to write a book on ASP.NET MVC, I
was already a frequent blogger on the topic and had published an article on the
framework in CoDe magazine. Even so, I knew writing a book would be a tremendous
challenge. This book has been in progress for over a year, and I am excited to see it
published. I learned quite a bit from Ben and Jimmy throughout this project, and I
learned so much more about the framework by writing about it. This knowledge has
direct and immediate benefit to our client projects.
Our hope is that our book will stay with you even after you have written your first
application. Writing a book published just after a 1.0 release is challenging because
many things are discovered after a technology has been out in the wild. Leveraging it
on client projects immediately has definitely helped increase the quality of informa-
tion contained in the book because it is derived from hands-on experience.
Although other platforms have benefited from Model-View-Controller frameworks
for many years, the MVC pattern is still foreign to many .NET developers. This book
explains how and when to use the framework; also the theory and principles behind
the pattern as well as complimentary patterns. We hope that this book will enlighten
your understanding of an indispensable technology that’s simple to learn.
JEFFREY PALERMO
xviii
acknowledgments
We’d like to thank Scott Guthrie for seeing the need in the .NET space for this frame-
work. Without his prototype, vision, and leadership, this offering would still not exist
in the .NET framework. We would also like to recognize the core ASP.NET MVC team
at Microsoft, headed by Phil Haack, the Program Manager for ASP.NET MVC. Other
key members of the ASP.NET MVC team are Eilon Lipton (Lead Dev), Levi Broderick
(Dev), Jacques Eloff (Dev), Carl Dacosta (QA), and Federico Silva Armas (Lead QA).
We would also like to extend our thanks to the large number of additional staff who
worked on packaging, documenting and delivering the ASP.NET MVC framework as a
supported offering from Microsoft. Even though this framework is small compared to
others, this move from Microsoft is shifting the mental inertia of the .NET portion of
the software industry.
This book employed three working authors, all consultants with multiple projects,
along with startup help and a chapter draft by Dave Verwer. The book efforttook over
a year and a half, starting with the first Community Technology Preview of the
ASP.NET MVC Framework. This dynamic required tremendous support from the staff
at Manning Publications. We would like to thank them for their patience and support
throughout the project. In particular, we would like to thank acquisitions editor
Michael Stephens and editor Tom Cirtin for their leadership. Michael saw the need
for this book and contacted me about writing it. Tom was very supportive and patient
and helped the three of us through our first book publication.
Our independent technical reviewers were outstanding. They offered advice and
opinionated viewpoints on each chapter during development, and without that input,
ACKNOWLEDGMENTS xix
the book would not be as good as we hope it is. Our sincere thanks goes to Phil Haack
for reviewing the manuscript and writing a brilliant foreword. Many thanks should
also go to Freedom Dumlao, who painstakingly reviewed each chapter to ensure the
message would apply in the best manner to the target audience. Jeremy Skinner was
also a boon to the project. Jeremy tested and retested every code listing and code sam-
ple in the book as well as in the many Visual Studio projects that come with the book.
His attention to detail, backed up by his vast experience with ASP.NET MVC and Mvc-
Contrib, has contributed greatly to this book.
Manning invited the following reviewers to read the manuscript at different stages
of development and to send their comments: Mark Monster, Andrew Siemer, Benja-
min Day, Frank Wang, Derek Jackson, Tim Binkley-Jones, Marc Gravell, Alessandro
Gallo, Josh Heyer, Peter Johnson, Jeremy Anderson, and Alex Thissen.
This book has also benefited from outside technical reviewers who volunteered to
read parts of the manuscript and provided feedback: Rod Paddock, Craig Shoemaker,
Hamilton Verissimo, Matt Hinze, Kevin Hurwitz, Blake Caraway, Nick Becker, Mahen-
dra Mavani, Eric Anderson, Rafael Torres, Eric Hexter, Tom Jaeschke, Matt Hawley,
and Sebastien Lambla.
Before this book went to print, a large number of people purchased the PDF edi-
tion of the book by participating in the MEAP, Manning’s Early Access Program. We
would like to thank those readers for their comments and participation early, and
throughout the manuscript portion of the project, especially Eric Kinateder, Ben
Mills, Peter Kellner, Jeff P., Orlando Agostinho, Liam McLennan, Ronald Wildenberg,
Max Fraser, Gudmundur.Hreidarsson, Kyle Szklenski, Philippe Vialatte, Lars Zeb,
Marc Gravell, Cody Skidmore, Mark Fowler, Joey Beninghove, Shadi Mari, Simone
Chiaretta, Jay Smith, Jeff Kwak, and Mohammad Azam.
JEFFREY PALERMO
I would like to thank my beautiful wife, Liana, for her support and patience through-
out this project. Liana gave birth to our daughter, Gwyneth Rose, shortly before the
book was started, and the motivation to spend more time with my growing family
pushed me to complete the book. Thanks also to my parents, Peter and Rosemary Pal-
ermo, for instilling in me a love of books and learning from an early age.
BEN SCHEIRMAN
My thanks and utmost appreciation go out to my amazing wife, Silvia. Her continued
support and encouragement of my extracurricular work led to writing this book in the
first place. I would also like to recognize one of my university mentors, Venkat Subra-
maniam. With his guidance, I found my passion in software development and strived
to learn more and push the envelope. He was an inspiration in my career. Finally I’d
like to thank my wonderful children, Andréa, Noah, and Ethan (and most recently
Isaac and Isabella), who showed immense patience and encouragement while their
dad was banging away at the keyboard in the late hours of the night.
ACKNOWLEDGMENTS
xx
JIMMY BOGARD
Thanks to my wife, Sara, without whose love, support, and patience, my contribution
to this project would not have been possible. Also, thanks to my family for putting up
with a strange little bookworm all those years. Finally, thanks to my high school com-
puter science teacher, Scotty Johnson, who showed me the rewards that a true passion
for the craft can bring.
xxi
about this book
The ASP.NET MVC Framework was a vision of Scott Guthrie in early 2007. With a proto-
type demonstration in late 2007 as well as a key hire of Phil Haack as the Senior Pro-
gram Manager of the feature team, Scott made the vision a reality. At a time when the
.NET community was becoming frustrated that other platforms had great MVC frame-
works like Tapestry, Rails, and so on, Web Forms was losing favor as developers strug-
gled to make it do things previously unimagined when it became public in 2001. Castle
MonoRail was a very capable framework and continues to have strong leadership
behind it, but the broader .NET industry needed a change from Web Forms. Phil
Haack, with his experience outside of Microsoft as well as in the open source commu-
nity, immediately came in and led the ASP.NET MVC Framework team to a successful 1.0
release that the .NET community is excited about.
ASP.NET MVC has the benefit of lessons learned from other popular MVC frame-
works such as Struts, WebWork, Tapestry, Rails, and MonoRail. It also came about as
C# starts to push away its fully statically typed roots. The language enhancements
introduced with .NET 3.5 have been fully leveraged in the ASP.NET MVC Framework,
giving it a huge advantage over frameworks that came before as well as all the Java
frameworks that are tied to the currently supported Java syntax.
For people who have a diversified software background, ASP.NET MVC is a great
addition to the Visual Studio development experience. For those who began their
software career with .NET 1.0 or later, it is a fundamental shift in thinking since they
grew up with Web Forms being “normal” web development.
This book attempts to start at a point that is past the documentation and online
tutorials available on the ASP.NET MVC website at http://www.asp.net/mvc/. If you are
ABOUT THIS BOOK
xxii
just getting started with ASP.NET, you will want to read some of the older books cover-
ing the ASP.NET pipeline and server runtime. Because ASP.NET MVC layers on to
ASP.NET, it is important to understand the fundamentals. If you are a current ASP.NET
developer, you will find that this book does not insult your intelligence. It is a fast-
paced book aimed at giving you the why and not just the how.
Since ASP.NET MVC is a new technology offering you can expect several books
to cover the topic. This is a framework that is not sitting still. Since its release in
March 2009, several books have been released, but the community is finding new
and better ways to use the framework. The newest ideas make their way to the Mvc-
Contrib project, and to public release frequently as new additions are contributed.
Because of this dynamic, this book covers ASP.NET MVC with MvcContrib sprinkled
throughout. The authors are all actively developing with the framework, and MvcCo-
ntrib plays a vital part in every application. This books aims to have a long-lasting
place on your bookshelf. The API will evolve, but the principles behind using an
MVC framework as well as the ways to structure URLs, tests, and application layers are
more durable. With this, we hope that this book serves not only as a rigorous foray
into ASP.NET MVC development but also as a guide toward developing long-lived web
applications on the .NET platform.
We hope that the arrival of this book is considered good timing because the text
was written with the perspective of the roadmap of ASP.NET MVC 2.0 in mind. With the
roadmap plans released and the first CTP of v2 already available, the techniques in this
book are useful now and are also relevant for ASP.NET MVC v2, which is quickly
approaching. We hope this book will help you start on your way to creating many
maintainable, long-lived applications on the new version of ASP.NET.
Who should read this book?
This book is written for senior developers working with ASP.NET. The authors are
senior and strong leaders in their companies, local community, and the industry. All
three authors are recognized by Microsoft with the Microsoft Most Valuable Profes-
sional (MVP) award. With that in mind, we felt it appropriate to write a book aimed at
senior members of the software team. With the market flooded with beginner books
and books that reformat online documentation and tutorials, we attempted to write a
book that might leave some beginners behind but at the same time challenge senior
developers and architects. Whether or not you are familiar with other MVC frame-
works, this book will push your knowledge further than you are accustomed to when
reading a technology book.
The book comes with a full reference implementation in production at http://
CodeCampServer.com. CodeCampServer was developed by the authors and is open
source with many other contributors at this time. CodeCampServer is an ASP.NET MVC
application aimed at hosting user group websites and websites for .NET user group
conferences, frequently called Code Camps. The codebase was developed using Onion
Architecture, domain-driven design, test-driven development, and inversion of con-
trol. The techniques espoused in the book are implemented in the project. Many of
ABOUT THIS BOOK xxiii
the code examples in the book are detailed explorations of parts of CodeCampServer.
Although the project will continue to evolve after this book is published, the princi-
ples with which it and the text were written are timeless and portable beyond a single
version of the technology.
Because in any real project, like CodeCampServer, you use many libraries for specific
things, we did not shy away from using these as well. We feel that avoiding other libraries
for the sake of simplicity also makes it difficult for the reader to apply the knowledge
gained while reading. With that in mind, we use popular libraries such as MvcContrib,
NAnt, NUnit, StructureMap, Windsor, Castle, RhinoMocks, Log4Net, NHibernate,
Tarantino, AutoMapper, Iesi.Collections and many others. Because real projects have a
collage of libraries, we felt that learning ASP.NET MVC in this realistic setting was most
appropriate. We have taken care to separate concerns when necessary. We always sepa-
rate data access from the domain model and the presentation layer, and we separate pre-
sentation model from views; you will not see simplistic examples such as performing a
query directly from a UI controller. This is bad practice in anything but the most trivial
applications such as that serving http://PartyWithPalermo.com (a three-page site).
Real applications have many screens, the embedding data access and other logic in the
UI is a recipe for a codebase that is very costly to maintain.
We’ve done our best to call out where we expect existing ASP.NET knowledge to tie
the example together, but if you find yourself wondering what an HTTP module is, you
will probably want to read one of the earlier ASP.NET books.
Roadmap
Chapter 1 throws the reader directly into code by picking apart the default project
template. After a primer on routes, the text moves through a simple controller and
view and moves to initial maintainability. The chapter follows up by covering the
basics of testing controllers.
Chapter 2 moves into the model. It covers not only the domain model of the appli-
cation but also the need for different types of models depending on usage, such as a
presentation model. Because the authors consider using a presentation model, com-
monly called view model, essential for the maintainability for nontrivial systems, it is
used right away.
Chapter 3 covers controller details. The controller can be very simple or quite
complex, and the text covers both. The chapter explores working with form values
and querystring values, and it covers model binding, which is one of the most-needed
abstractions for ASP.NET to date. Chapter 3 concludes after outlining all the available
extension points that are built in.
Chapter 4 gives further insight into views. After outlining the key abstractions in
the default view engine, it pulls the reader along to essential concepts such as layouts,
partial views, and building your own validation and HTML helpers.
Chapter 5 goes deeper than you will ever need into routing. Although most proj-
ects will not need this amount of advanced routing, we explore the topic thoroughly.
We cover the why and not just the how of crafting URLs. From designing a URL schema
ABOUT THIS BOOK
xxiv
to adding dynamic routes, this chapter is a comprehensive guide to the most flexible
routes you will need.
Chapter 6 explores the many ways to customize and extend the ASP.NET MVC
Framework. It starts with custom route handlers and moves to when, why, and how to
create your own controller factory. Two Inversion of Control containers are covered in
the controller factory section: Windsor and StructureMap. Because most nontrivial
applications will want to use a custom controller factory, this section is covered thor-
oughly. Next the chapter moves through the ways to extend the controller with action
invokers and filters. After a custom view engine and using the new T4 templates, the
reader will have the full picture of the available extension points.
Chapter 7 communicates ways to scale the architecture for more complex sites.
The first is solving the problem of large controller actions and how to move multiple,
ill-placed responsibilities out of the controller. View helpers are also covered in more
detail as well as techniques for segmenting large views into a number of cohesive
smaller ones. The chapter also covers larger issues encountered with action filters.
Chapter 8 offers ways to leverage existing ASP.NET features in an ASP.NET MVC appli-
cation. The text covers how to use existing server controls, then moves to caching, both
output caching and using request level caching provided by HttpContext.Items. It then
moves through tracing, health monitoring, site maps, personalization, localization,
linq, cookies, session state, and configuration. Because ASP.NET MVC is an add-on to
ASP.NET and not a replacement, this chapter ensures the reader understands where all
these existing features fit.
Chapter 9 has been one of the most popular chapters in the early access program
because now, in mid-2009, AJAX is a hot topic. We first lay down our opinionated view
on AJAX and then outline the most common uses and techniques for it starting with
simple HTML replacement. The chapter covers implementing a REST API with con-
trollers as well as some of the third-party libraries and controls available for AJAX. The
chapter also outlines ways to make controller actions automatically support AJAX.
Chapter 10 covers hosting and deployment. Though not as sexy of a topic as
AJAX, it is critical to understand how to deploy applications built on this framework
to IIS5/6/7/7.5. All versions are covered in detail as well as the implications of using
extensions, wildcard mappings, and URL rewriting. After covering XCopy deploy-
ment, the chapter delivers techniques for managing production and development
environment settings. The chapter closes out with an autodeployment example that
is similar to how CodeCampServer is autodeployed in the wild.
Chapter 11 explores MonoRail and Ruby on Rails as a comparison and benchmark
against ASP.NET MVC. It starts out with MonoRail and covers validation, data access
with ActiveRecord, as well as the view engine choices. Rails follows closely on its heels
with “The Rails Way,” ActiveRecord and ActionPack. The purpose of the chapter is to
give the reader some familiarity with competing MVC frameworks because good ideas
come from everywhere.
ABOUT THIS BOOK xxv
Chapter 12 uses the controversial title, “Best Practices.” We outline the context
that these practices support. We outline best practices for controllers, views, routes,
and testing. Each topic has very opinionated recommendations borne from real-world
usage of ASP.NET MVC in this type of application.
Chapter 13 provides four comprehensive recipes that can be easily implemented
on your project. One of the larger chapters, it starts with using jQuery for an autocom-
plete text box and then moves on to how to implement automatic client-side data vali-
dation. Data access with NHibernate is the next recipe and provides a full vertical slice
implementation for calling data access backed by NHibernate from controllers. It out-
lines how to map and configure NHibernate as well as some basic mapping and query-
ing techniques. The chapter wraps up with a full Spark view engine implementation
for those who don’t like the tag format of Web Forms.
Code conventions and downloads
All source code in listings or in text is in a fixed-width font like this to separate it
from ordinary text. Code annotations accompany many of the listings, highlighting
important concepts. In some cases, numbered bullets link to explanations that follow
the listing.
The source code for the examples in this book is available online from the pub-
lisher’s website at http://www.manning.com/ASP.NETMVCinAction.
Author Online
The purchase of ASP.NET MVC in Action includes free access to a private web forum run
by Manning Publications, where you can make comments about the book, ask techni-
cal questions, and receive help from the author and from other users. To access the
forum and subscribe to it, point your web browser to http://www.manning.com/
ASP.NETMVCinAction.
This page provides information about how to get on the forum once you’re regis-
tered, what kind of help is available, and the rules of conduct on the forum. Man-
ning’s commitment to our readers is to provide a venue where a meaningful dialogue
between individual readers and between readers and the authors can take place. It’s
not a commitment to any specific amount of participation on the part of the authors,
whose contribution to the book’s forum remains voluntary (and unpaid). We suggest
you try asking them some challenging questions, lest their interest stray!
The Author Online forum and the archives of previous discussions will be accessi-
ble from the publisher’s website as long as the book is in print.
xxvi
about the authors
JEFFREY PALERMO is the CTO of Headspring Systems. Jeffrey spe-
cializes in Agile management coaching and helps companies
double the productivity of software teams. He is instrumental
in the Austin software community as a member of AgileAustin
and a director of the Austin .NET User Group. Jeffrey has been
recognized by Microsoft as a “Microsoft Most Valuable Profes-
sional” (MVP) in Solutions Architecture for five years and par-
ticipates in the ASPInsiders group, which advises the ASP. NET
team on future releases. He is also certified as a MCSD.NET and ScrumMaster. Jeffrey
has spoken and facilitated at industry conferences such as VSLive, DevTeach, the Micro-
soft MVP Summit, various ALT.NET conferences, and Microsoft Tech Ed. He also speaks
to user groups around the country as part of the INETA Speakers’ Bureau. His web sites
areheadspringsystems.comandjeffreypalermo.com.HeisagraduateofTexasA&M Uni-
versity, an Eagle Scout, and an Iraq war veteran. Jeffrey is the founder of the Code-
CampServer open-source project and a cofounder of the MvcContrib project.
Jeffrey Palermo is responsible for the popular Party with Palermo events that precede
major Microsoft-focused conferences. Started in June of 2005, Party with Palermo has
grown in popularity and size. Typical events host hundreds of people for free drinks and
food and door prizes. It is the perfect way to hook up with friends and colleagues before
the conference week begins. You can see past and upcoming parties at http://party-
withpalermo.com where the website has run on ASP.NET MVC since October 2007.
ABOUT THE AUTHORS xxvii
BEN SCHEIRMAN is a software developer specializing in .NET.
He has worked extensively on the web on various platforms
and languages. Ben is a Microsoft MVP, Microsoft ASP Insider,
and Certified ScrumMaster. When not programming, Ben
enjoys speaking, blogging, spending time with his wife and
five wonderful children, or voiding warranties on his latest
gadgets. Ben is a Principal Consultant with Sogeti in Hous-
ton, Texas. Read his blog online at http://flux88.com.
JIMMY BOGARD is a Principal Consultant at Headspring Systems.
He is an agile software developer with six years of professional
development experience. He has delivered solutions from
conception to production for many clients. The solutions
delivered by Jimmy range from shrink-wrapped products to
enterprise ecommerce applications for Fortune 100 custom-
ers. He is also a Microsoft Certified Application Developer
(MCAD) and is an active member in the .NET community, lead-
ing open-source projects, giving technical presentations and facilitating technical book
clubs. Currently, Jimmy is the lead developer on the NBehave project, a Behavior-Driven
Development framework for .NET, AutoMapper, a convention-based object-to-object
mapper and the facilitator of the Austin Domain-Driven Design Book Club. Jimmy is a
member of the ASPInsiders group, and received the “Microsoft Most Valuable Profes-
sional” (MVP) award for ASP.NET in 2009.
About the technical reviewers
JEREMY SKINNER lives in the UK and works as a software devel-
oper. Most of his work involves writing web applications using
ASP.NET and C#. He is involved with several open-source proj-
ects including MvcContrib, Fluent Validation, and Fluent
Linq to Sql.
Jeremy has been invaluable to this book project by reviewing
each paragraph of text, each figure, and code example. He
found and corrected numerous errors, and this book would
not be a good book without him. He is capable of being an author himself, and we fully
expect full books out of him in the future. Jeremy’s experience with the ASP.NET MVC
framework as well as popular third-party frameworks such as Castle has made him a
strong reviewer. His blog can be found at http://www.jeremyskinner.co.uk/.
FREEDOM DUMLAO is a software engineer working primarily in .NET. He has a blog at
http://weblogs.asp.net/FreedomDumlao/. Freedom reviewed the first drafts of each
chapter and made critical suggestions for improvement. His perspective was very valu-
able to the quality of the book.
xxviii
about the cover illustration
The figure on the cover of ASP.NET MVC in Action is captioned “L’Habitant de Ver-
sailles” which means a resident of the town of Versailles. Today, Versailles is a suburb
of Paris with a population of over 90,000, but in the past it was famous both as the cap-
ital city of France for a number of years in the 17th and 18th centuries and for the Pal-
ace of Versailles around which the city grew.
The illustration is taken from a 19th century edition of Sylvain Maréchal’s four-
volume compendium of regional dress customs published in France. Each illustration
is finely drawn and colored by hand. The rich variety of Maréchal’s collection reminds
us vividly of how culturally apart the world’s towns and regions were just 200 years ago.
Isolated from each other, people spoke different dialects and languages. In the streets
or in the countryside, it was easy to identify where they lived and what their trade or
station in life was just by what they were wearing.
Dress codes have changed since then and the diversity by region, so rich at the
time, has faded away. It is now hard to tell apart the inhabitants of different conti-
nents, let alone different towns or regions. Perhaps we have traded cultural diversity
for a more varied personal life—certainly for a more varied and fast-paced technolog-
ical life.
At a time when it is hard to tell one computer book from another, Manning cele-
brates the inventiveness and initiative of the computer business with book covers
based on the rich diversity of regional life of two centuries ago, brought back to life by
Maréchal’s pictures.
1
Getting started with
the ASP.NET MVC
Framework
Depending on how long you’ve been building web applications on the Microsoft
platform, you’ll relate to some or all of the following pain. In the 1990s, developers
built interactive websites using executable programs that ran on a server. These pro-
grams (Common Gateway Interface [CGI] was a common technology at the time)
accepted a web request and were responsible for creating an HTML response. Tem-
plating was ad hoc, and the programs were difficult to write, debug, and test. In the
late 1990s, Microsoft, after a brief stint with HTX templates and IDC connectors,
introduced Active Server Pages, or ASP. ASP brought templating to web applications.
This chapter covers
■ Running the starter project
■ Progressing through Hello World examples
■ Routing basics
■ Unit testing basics
2 CHAPTER 1 Getting started with the ASP.NET MVC Framework
The server page was an HTML document with dynamic script mixed in. Although this
was a big step forward from the alternatives, the world soon saw massive server pages
with code indecipherable from the markup.
In early 2002, along came ASP.NET and the Web Forms Framework. Web Forms
were a complete shift for ASP developers, partly because they moved most program
logic into a class file (called a code-behind) and replaced the HTML markup with
dynamic server controls written in an XML syntax. Although performance increased,
and the debugging experience improved, new problems arose.
The new server-side postback event lifecycle caused newsgroups to explode with
activity as confused developers searched for that magic event in which to add those two
simple lines of code necessary to make the page work as needed. ViewState, although
good in theory, broke down as the application scaled with complexity. Simple pages
surpassed 100KB in size, as the entire state of the application had to be stored in the
output of every generated page. Development best practices were ignored as tools like
Visual Studio encouraged data access concerns like SQL queries to be embedded
within view logic. Perhaps the greatest sin of the Web Forms Framework was the tight
coupling to everything in the System.Web namespace. There was no hope of unit test-
ing any code in the code-behind file, and today we see Page_Load methods that take
several trees to print. Although early versions of Web Forms had some drawbacks,
ASP.NET and the larger .NET Framework have made huge inroads into the web appli-
cation market. Today we see major websites such as CallawayGolf.com, Dell.com, News-
week.com, WhiteHouse.gov, and Match.com all running on ASP.NET. The platform has
proven itself in the marketplace, and when combined with IIS running on Windows,
ASP.NET can easily support complex web applications running in large data centers.
The ASP.NET MVC Framework leverages the success of ASP.NET and Web Forms to pro-
pel ASP.NET forward as a leader in the web application development space.
The ASP.NET MVC Framework has been introduced to simplify the complex parts
of Web Forms application development while retaining the power and flexibility of
the ASP.NET pipeline. The ASP.NET infrastructure and request pipeline, introduced in
.NET 1.0, stay the same, and ASP.NET MVC provides support for developing ASP.NET
applications using the Model-View-Controller web presentation pattern. The concerns
of the data model, the application logic, and data presentation are cleanly separated,
with the application logic kept in a class separated from hard dependencies on how
the data will be presented. Server pages have become simple views, which are nothing
more than HTML templates waiting to be populated with objects (models) passed in
by the controller. The postback event lifecycle is no more, and ViewState is no longer
necessary. In this chapter, we’ll walk through your first lines of code built on top of the
ASP.NET MVC Framework. After this primer, you’ll be ready for more advanced topics.
In this chapter, and throughout the book, we assume that the reader has knowl-
edge of ASP.NET. If you’re new to ASP.NET, please familiarize yourself with the ASP.NET
request pipeline as well as the .NET runtime. Throughout this chapter, we’ll take you
through creating an ASP.NET MVC Framework web application project, creating your
3
Picking apart the default application
first routes, controllers, and views. We’ll comb through the default application and
explain each part. Then we’ll extend it, and you’ll create your first controller and
view. First, let’s explore the MVC pattern and the default application template pro-
vided with the framework.
1.1 Picking apart the default application
In this section, we’ll explain what the MVC pattern is and create our first ASP.NET
MVC Web Application. We’ll focus first on the controller because in the Model-View-
Controller triad, the controller is in charge and decides what model objects to use
and what views to render. The controller is in charge of coordination and executes
first when the web request comes in to the application. The controller is responsible
for deciding what response is appropriate for the request.
The Model-View-Controller pattern is not new. A core tenet of the MVC pattern is
to separate control logic from the view, or a screen. A view is only responsible for ren-
dering the user interface. By separating domain logic and decoupling data access and
other calls from the view, the UI can stay the same even while logic and data access
changes within the application. Figure 1.1 shows a simple diagram of the MVC triad.
Note that the controller has a direct relationship with the view and the model, but the
model does not need to know about the controller or the view. The web request will
be handled by the controller, and the controller will decide which model objects to
use and which view objects to render.
Integrating with or migrating from ASP.NET Web Forms applications
Can we create screens that leverage the ASP.NET MVC Framework while others con-
tinue to work using Web Forms? Of course we can. They can run side by side until the
entire application is MVC. Using the MVC framework is not an all-or-nothing proposi-
tion. There are many, many ASP.NET applications in production using Web Forms. If
a software team wants to migrate the application from Web Forms to ASP.NET MVC,
it’s possible to do a phased migration and run the two side by side in the same App-
Domain. ASP.NET MVC does not replace core ASP.NET libraries or functionality. Rath-
er, it builds on top of existing ASP.NET capabilities. The UrlRoutingModule that we
registered in the web.config file causes an incoming URL to be evaluated against the
existing routes. If a matching route is not found, ASP.NET will continue on and use
Web Forms to fill the request, so it’s pretty simple to mix and match features during
a migration or for the purpose of application extension.
Although Web Forms is not going away any time soon, we believe that controllers, ac-
tions, and views will be the preferred way to write ASP.NET applications going into the
future. Although Microsoft will continue to support both options (and active develop-
ment on the next version of Web Forms continues), we believe that the ASP.NET MVC
Framework will be favored over Web Forms much like we see C# favored over VB in
documentation, industry conferences, and technical books.
4 CHAPTER 1 Getting started with the ASP.NET MVC Framework
To begin, we’ll open up Visual Studio 2008 SP1 and create our project. The edition of
Visual Studio 2008 makes a difference. Although there are some workarounds to
using the ASP.NET MVC Framework without SP1, System.Web.Abstractions.dll and
System.Web.Routing.dll are in the GAC (global assembly cache) as of SP1. You can
use Visual Studio 2008 Professional, a Team Edition SKU, or Visual Web Developer
Express SP1. Note that the ASP.NET MVC Framework builds on top of Web Application
Projects, and although it’s possible to make it work with websites, the development
experience is optimized for use with Web Application Projects.
NOTE You must already have Visual Studio 2008 SP1 or Visual Web Develop-
er 2008 SP1, .NET 3.5 SP1, and the ASP.NET MVC Framework installed to
proceed. The MVC framework is an independent release that builds
upon .NET 3.5 Service Pack 1. The examples in this book will use Visual
Studio 2008 SP1, but you can find information on using the free Visual
Web Developer Express 2008 SP1 on the ASP.NET MVC website: http://
www.asp.net/mvc/.
We’ll begin in Visual Studio 2008 Professional SP1 by creating a new ASP.NET MVC
Web Application project. When you pull up the New Project dialog, make sure you
have .NET Framework 3.5 selected. If you have .NET Framework 3.0 or 2.0 selected,
Visual Studio will filter the list, and you’ll not see the project template for ASP.NET
MVC Web Application. Now that you understand the basics of the pattern and how to
install the MVC framework, we’ll dive into our first project.
1.1.1 Creating the project
Creating your first ASP.NET MVC Web Application project will be one of the simplest
things you do in this chapter. In Visual Studio 2008, when you have .NET Framework 3.5
selected as the target framework, you’ll see a new project template named ASP.NET MVC
Web Application. Choose this project template. The new project dialog will look like
that shown in figure 1.2.
We’re going to be working with a C# ASP.NET MVC Web Application project. You
have two options for creating the project. When you click OK, the IDE will ask you about
creating a test project. Decide if you’d like it done for you or if you’d rather create the
unit test project yourself. For this example, we’ll choose the ASP.NET MVC Web Appli-
cation with the test project. Figure 1.3 shows the solution structure of the default Visual
Studio template. Since this is not a beginners’ book, we’ll skip the hand-holding and go
straight into the project.
Model
Controller
View
Figure 1.1 A simple diagram depicting the
relationship between the Model, View, and
Controller. The solid lines indicate a direct
association, and the dashed lines indicate an
indirect association (graphic and description
used with permission from Wikipedia).
5
Picking apart the default application
NOTE More ASP.NET MVC starter kits and sample applications are available from
the community on the ASP.NET website. At the time of writing, http://
www.asp.net/community/projects/ and http://www.asp.net/mvc/ have
several starter kits and sample applications for starting ASP.NET MVC proj-
ects (as well as ASP.NET Web Forms starter kits). The options include
■ Kigg Starter Kit—a Digg-like application
■ Contact Manager Sample Application
■ Storefront Starter Kit
Although the starter kits are quite basic, you should also check out more
complete starter kits like those found at http://CommunityForMvc.net.
This site contains a bare-bones template as well as one complete with
MvcContrib, StructureMap, NHibernate, NUnit, NAnt, AutoMapper,
Tarantino, Naak, NBehave, Rhino Mocks, WatiN, Gallio, Castle, 7zip,
and more.
If you’re new to .NET development in general, you should first become
familiar with Microsoft’s default template. Then use a more robust starter
kit or sample application provided by the community to have a better
jumping-off point. When you have mastered the framework, think about
contributing your own starter kits.
Figure 1.2 The MVC Web Application project is a project template added to the C# and VB.NET sections
of the New Project dialog. It’s only available when you have .NET Framework 3.5 selected as the target
framework.
6 CHAPTER 1 Getting started with the ASP.NET MVC Framework
Figure 1.3 The default structure for a
web application project using the
ASP.NET MVC Framework uses
conventions for the placement of files.
The first thing to notice is that in contrast to
the very sparse structure of a default Web
Forms project template, the default MVC tem-
plate creates several folders: Content, Control-
lers, Models, Scripts, and Views. These folders
represent part of the MVC application develop-
ment conventions, which, if adhered to, can
make the experience of developing with the
MVC framework a breeze.
For now, the most important of these fold-
ers to become familiar with are the three which
have been named after their MVC pattern coun-
terparts (the Model, View, and Controller fold-
ers). As you’d expect, the purpose of each of
these folders is to provide logical separation of
the three MVC concerns, as well as to tap into a
nice feature of Visual Studio that will automati-
cally namespace any class created within a
folder with that folder’s name.
The Controllers folder is probably the least
interesting. The folder should contain only
classes which are to be used as controllers, or
base classes and interfaces that controllers
might inherit from. The Views folder is special
because it will contain code that will probably
be the most familiar to Web Forms developers.
The Views folder contains the aspx (views),
ascx (partial views), and master pages used to
present the data. Typically you’ll have a folder
inside the Views folder for each controller
which will contain views intended to be used specifically by that controller, as well as a
Shared folder to contain shared views.
The Happy Path
ASP.NET MVC developers (and developers using other convention-centric frame-
works) will often mention the Happy Path. This refers to the notion that following the
MVC framework’s conventions will make the developer’s experience both enjoyable
and relatively painless. The MVC framework does not require you to adhere to any
particular convention, but the farther you stray from the Happy Path the greater the
effort will be required by the developer. The MvcContrib project enhances the path,
and you’ll certainly find ways to enhance it in your system. Staying on the path gains
you a great deal in consistency.
7
Picking apart the default application
For most nontrivial projects, you probably won’t place your models in the Models
folder. Generally speaking it’s a best practice to keep your domain model in a separate
project so that other applications can use it without taking a dependency on your MVC
application. We recommend that you put only presentation concerns in the Web
Application project.
In the default project, you may be familiar with the Default.aspx file that is pro-
vided for you, and we’ll discuss shortly why it is there. First, we must understand the
concept of a route.
1.1.2 Your first routes
Routes will be discussed in great detail in chapter 5; however, you should be aware of
some route basics to move through this section. Although Web Forms mandated a
strict convention for URLs, the MVC framework provides a mechanism to allow devel-
opers to handcraft URLs, and have them map automatically to an object in the system
that can handle the incoming web request. Routing was added to ASP.NET in the .NET
Framework 3.5 Service Pack 1 release, and is available to all ASP.NET applications. The
Global.asax.cs file contains basic routes that are provided with the MVC Web Appli-
cation project to help you get started. Before continuing, we should define a route.
A route is the complete definition for how to dispatch a web request to a control-
ler, usually using the System.Web.Mvc.MvcRouteHandler. In the past we have had little
control over message dispatching without resorting to external tools like ISAPI filters
or carefully crafted HttpModules for URL rewriting. With Web Forms, the URL of the
web request was tightly coupled to the location of the page handling the request. If
the page was named Foo.aspx in a folder named Samples, the URL was sure to be
something like http://MvcContrib.org/Samples/Foo.aspx. Many teams have
resorted to URL rewriting to wrangle some control over the URLs and how they are
produced. With the ASP.NET MVC Framework, and ASP.NET 3.5 SP1 in general, routes
are first-class citizens that can be managed directly in the web application. We start
with defining how we want our URLs structured. The project template gives us a few
routes to start, as shown in listing 1.1.
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Ch1GettingStarted
{
public class MvcApplication : HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
Listing 1.1 Default routes for a new project
Route name
URL with parameters
8 CHAPTER 1 Getting started with the ASP.NET MVC Framework
new {controller = "Home", action = "Index", id = ""}
);
}
protected void Application_Start ()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
Routes must be defined before any request can be received by the application, so the
project template adds the routes to the Application_Start method in the Global.
asax.cs file. Later in the book, you’ll see that we do not leave the routes in this location
except for the most trivial of web applications.
NOTE We’ll follow long-standing best practices of separation of concerns (SoC) and
the single responsibility principle, or SRP, by moving the routes to a dedi-
cated location separated by an interface. We’ll go further into these
principles later, but, in short, the responsibility (or concern) of the
Application_Start method is to kick off operations that must happen at
the beginning of the application’s life. The responsible approach is to
avoid performing every bit of work that must happen on start. Any opera-
tions that must happen when the application starts should reside in sepa-
rate classes and merely be called in the appropriate order in the
Application_Start method.
Note that the URL portion of the route is simply a matching mecha-
nism for the request. If the URL matches a particular route, then we spec-
ify what controller should handle the request and what action method
should execute. You can create as many routes as you like, but one route
is provided for you. This route has the template, {controller}/
{action}/{id}.
The route with the template {controller}/{action}/{id} is a generic
one and can be used for many, many different web requests. Tokens are
denoted by the inclusion of {braces}, and the word enclosed in braces
matches a value the MVC framework understands. The most common val-
ues that we’ll be interested in are controller and action. The
controller route value is a special value that the System.Web.Mvc.
MvcHandler class uses to call into the IControllerFactory interface.
This is also the route we’ll be using for the rest of the chapter, so we’ll be
content with a URL in the form of http://MvcContrib.org/controller-
name/actionname. The basic route handler is an instance of IRoute-
Handler named MvcRouteHandler. We have complete control and could
provide our own implementation of IRouteHandler if we wished, but
we’ll save that for a later chapter.
Before we spin up our first controller, let’s examine what is different about the
web.config file in an MVC Web Application project. The differences are easy to spot.
Parameter defaults
9
Picking apart the default application
Just look for “routing” or “MVC.” One difference we see is that a new IHttpModule is
registered in the config file. We see the UrlRoutingModule in listing 1.2.
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule,
System.Web.Routing, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" />
The UrlRoutingModule evaluates a request and checks if it matches a route that is
stored in the RouteTable. If the route matches, it overrides the default handler
(IHttpHandler) for the request so that the MVC framework handles the request.
We’re going to examine our first controller as a means to handle a route for the
URL /home. In the next section you’ll see how all the pieces of the starter project
fit together.
1.1.3 Running with the starter project
We’re going to move through the
starter project quickly looking at each
piece of provided code. Each serves as
an example of how to fit code together
when writing an application with the
presentation layer powered by the
ASP.NET MVC Framework. Before look-
ing at code, run the web application by
pressing CTRL + F5, and you should see
a screen that resembles figure 1.4.
The starter project includes some
navigation, a Log On, and content.
The CSS provides simple formatting
on top of XHTML. Notice the URL in the address bar is /. "/home" also will bring up
the same page since our route specifies “home” as the default controller. This URL
does not have an extension, so if you’re planning on running your application on IIS
6, you must either add a wildcard mapping or install an ISAPI filter that provides this
functionality. Deployment to IIS 6 will be covered in more detail in chapter 10.
Since you’re familiar with the ASP.NET request pipeline, we’ll briefly move through
how this request makes its way to an ASP.NET MVC controller. The following outlines
how the request moves through ASP.NET, to the controller, and through the view:
1 Request comes in to /Home.
2 IIS determines the request should be handled by ASP.NET.
3 ASP.NET gives all HttpModules a chance to modify the request.
4 The UrlRoutingModule determines that the URL matches a route configured in
the application.
Listing 1.2 Unique addition to the web.config file
Figure 1.4 The starter project comes with a basic
layout and CSS.
10 CHAPTER 1 Getting started with the ASP.NET MVC Framework
5 The UrlRoutingModule gets the appropriate IHttpHandler from the IRoute-
Handler that is used in the matching route (most often, MvcRouteHandler) as
the handler for the request.
6 The MvcRouteHandler constructs and returns MvcHandler.
7 The MvcHandler, which implements IHttpHandler, executes ProcessRequest.
8 The MvcHandler uses IControllerFactory to obtain an instance of ICon-
troller using the "controller" to route data from the route {controller}/
{action}/{id}.
9 The HomeController is found, and its Execute method is invoked.
10 The HomeController invokes the Index action.
11 The Index action adds objects to the ViewData dictionary.
12 The HomeController invokes the ActionResult returned from the action,
which renders a view.
13 The Index view in the Views folder displays the objects in ViewData.
14 The view, derived from System.Web.Mvc.ViewPage, executes its Process-
Request method.
15 ASP.NET renders the response to the browser.
These steps represent the simplified life of a request handled by the ASP.NET MVC
Framework. If you’re curious about the details, you can browse the source code at
http://www.codeplex.com/aspnet. The 15 steps are sufficient for understanding how
to write code based on the ASP.NET MVC Framework, and most of the time you’ll need
to pay attention only to the controller and the view. You have already seen the route
used in the starter project. Let’s look at the HomeController, shown in listing 1.3.
using System.Web.Mvc;
namespace Ch1GettingStarted.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData ["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
}
}
Notice how simple the controller is. There is not much generated code to wade
through, and each action method returns an object derived from ActionResult. This
Listing 1.3 The HomeController
B Default action
for controller
C
Return default
view for action
Another action
method
11
Picking apart the default application
controller derives from System.Web.Mvc.Controller B. You’ll probably find this
base class adequate, but there are others to choose from in the MvcContrib project,
and as time goes on, the community will likely make many more available. It also may
be a good practice to create your own layer supertype to use in your application.
Inside each action method, you’ll typically put some objects into a dictionary called
ViewData C. This dictionary will be passed to the view upon rendering. The controller
can provide any objects the view requires in this ViewData dictionary; the primary
object the view will render should be assigned to the ViewData’s Model property. This
can be done automatically by passing the object into the controller’s View() method.
In the starter project, the objects are simple strings, but in your application, you’ll use
more complex objects like those in figure 1.5.
Each default action returns the result of the
View()method,whichreturnsaSystem.Web.Mvc.
ViewResult object. This ActionResult subclass
willlikelybeacommonresultgiventhatyourappli-
cations will have many screens. In some cases,
you may use the other ActionResult types as
shown in figure 1.5. Your controller action can
return any type. The Controller base class will call
ToString() on your object and return that string
in a ContentResult object. Next, let’s look at the
view shown in listing 1.4, which can be found in the
project in the following path: /Views/Home/
Index.aspx.
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent"
➥ runat="server">
Home Page
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent"
➥ runat="server">
<h2><%= Html.Encode(ViewData ["Message"]) %></h2>
<p>
To learn more about ASP.NET MVC visit
<a href="http://asp.net/mvc" title="ASP.NET MVC
Website">http://asp.net/mvc</a>.
</p>
</asp:Content>
The view shown in listing 1.4 is the one rendered in the browser screenshot shown in
figure 1.4. With the MVC framework, markup files do not use a code-behind file. Since
the view uses the Web Forms templating engine, you could use it, but by default just a
simple markup file is generated.
Listing 1.4 A simple view
Figure 1.5 Classes that derive from
ActionResult. This screenshot is from
Red Gate’s .Net Reflector.
12 CHAPTER 1 Getting started with the ASP.NET MVC Framework
This view uses a master page, as you can see in the MasterPageFile attribute in the
Page directive. The master can be specified by the controller for compatibility with
many view engines, but some view engines support the view specifying the layout,
which is the case with the Web Forms view engine, the default view engine that ships
with the MVC framework.
NOTE: A ViewResult leverages the IViewEngine interface, which is an abstrac-
tion that allows the usage of any mechanism for rendering a view. View
engines will be covered in more depth later, but some alternatives can be
found in the MvcContrib open source project.
In the body of this view, the server-side tags are pulling objects out of ViewData and
rendering them in line with HTML. The responsibility of the view is to take objects in
ViewData and render them for consumption by the user. The view does not decide
what to render, only how to render. The controller has already decided what needs to
be rendered.
In listing 1.5, examine the code of the layout. You immediately see that it’s a plain
master page, not much different from those found in Web Forms. The difference is
that master pages in MVC projects do not need to use code-behind files.
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/
TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" />
</title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>My MVC Application</h1>
</div>
<div id="logindisplay">
<% Html.RenderPartial("LogOnUserControl"); %>
</div>
<div id="menucontainer">
<ul id="menu">
<li><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li><%= Html.ActionLink("About", "About", "Home")%></li>
</ul>
</div>
</div>
<div id="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
Listing 1.5 The starter project master page
Render
another view
Render hyperlinks
13
Picking apart the default application
<div id="footer">
</div>
</div>
</div>
</body>
</html>
The master page here is in charge of navigation. It uses view helpers (Html.Action-
Link in this case) to render the links. View helpers are available for most common
dynamic needs and for all form elements. More view helpers are available in Mvc-
Contrib, and third-party component vendors will not be far behind in offering com-
mercial view helpers.
Now that you have seen how the code in the starter project fits together, let’s see
how to test the controller code. View code will still need to be tested with a tool like
Selenium, Watir, or WatiN, but controller code can easily be test-driven since it’s
decoupled from the view and the ASP.NET runtime. When you start a new MVC proj-
ect, a dialog will ask you which unit testing framework you’d like to use.
If you’re using Visual Studio 2008 Professional then Visual Studio Unit Test will
already be in the list and selected. Most common unit testing frameworks have
templates that show up in the list when they are installed. For now we’ll look at using
MSTest (Visual Studio Unit Test), but we recommend using NUnit. If you’re just start-
ing out in automated testing, any mainstream framework will do. Listing 1.6 shows an
MSTest test method included in the default test project template.
using System.Web.Mvc;
using Ch1GettingStarted.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Ch1GettingStarted.Tests.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
HomeController controller = new HomeController();
ViewResult result = controller.Index() as ViewResult;
ViewDataDictionary viewData = result.ViewData;
Assert.AreEqual("Welcome to ASP.NET MVC!",viewData["Message"]);
}
}
}
Believe it or not, we have walked through the complete ASP.NET starter project, and you
now know the basics of the new framework. Obviously, we’ll be moving into more com-
plex topics throughout this book, and if any topic along the way does not sink in com-
pletely, please crack open Visual Studio and poke around while reading. Working with
Listing 1.6 The unit test for the Index action
14 CHAPTER 1 Getting started with the ASP.NET MVC Framework
the code directly, along with reading this text, will give you a solid understanding of this
technology. In fact, now is a great time to download the code samples for this book and
open your IDE default application.
1.2 Your first ASP.NET MVC controller from scratch
Look at listing 1.7 to understand how a web request is processed by the controller.
Note the only requirement is to implement the IController interface.
using System;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication.Controllers
{
public class HelloWorld1Controller : IController
{
public void Execute(RequestContext requestContext)
{
requestContext.HttpContext.Response.Write(
"<h1>Hello World1</h1>");
}
}
}
As with everything in the ASP.NET MVC Framework, there is very little the developer
must do to create custom functionality. In the case of the controller, the only—I will
say it again—the only requirement is that the class implement the IController inter-
face B. This interface only requires that you implement a single method: Execute.
How you handle the request is entirely up to you. In the controller in listing 1.7, we’re
intentionally violating all principles of sensible programming as well as the Law of
Demeter in order to get the message “Hello World” written out to the screen as quickly
as possible. In this case, I’ve chosen not to make any use of a view. Rather, I’m formu-
lating incomplete HTML markup and directing it to the response stream. We’ll run
the sample and note the output in figure 1.6. In the code solution that comes with the
book, you can find HelloWorld1ControllerTester that illustrates how you’d unit test
a simple controller like this.
Listing 1.7 Our first controller
B
Figure 1.6 Our web application
running in the browser. Note the
simple URL and the absence
of .aspx.
15
Your first ASP.NET MVC controller from scratch
Listing 1.7 shows the absolute and complete power you have when creating a controller
class. It’s very important to have complete control; however, most of the time, we’re
working in a handful of scenarios that repeat over and over. For these scenarios, the
product provides a base class that gives extra functionality. The base class for these com-
mon controllers is System.Web.Mvc.Controller. It implements the Execute method
for us and uses the route values to call different action methods depending on the URL
and the route defaults.
NOTE System.Web.Mvc.Controller is only one option to choose as a base class
for your controllers. As mentioned earlier, it’s often appropriate to cre-
ate your own layer supertype for all of your controllers. This type can
inherit from System.Web.Mvc.Controller, implement IController, or
derive from any other controller base class.
Our first use of the Controller base class will need only one action method, and we’ll
go with the convention for the default action and call it Index. Observe in listing 1.8
what our controller looks like while we leverage the Controller base class. This base
class implements the IController interface for us and provides the capability of
invoking action methods based on the current Route.
using System.Web.Mvc;
namespace MvcApplication.Controllers
{
public class HelloWorld2Controller : Controller
{
public string Index()
{
return "<h1>Hello World2</h1>";
}
}
}
The public Index action method is all that is necessary for this controller to be web-call-
able. Simple content action methods need not return ActionResult. Returning any
other type will result in that object being rendered as content to the response stream.
If we point our browser to /HelloWorld2, we’ll see that our controller sends the
same response to the browser as shown in figure 1.7:
Listing 1.8 Using the Controller base class
Inherit from
Controller
Figure 1.7 The web page has
the same output as before. The
end result is the same even
though the controller implemen-
tation has evolved.
16 CHAPTER 1 Getting started with the ASP.NET MVC Framework
Now that we know how to craft a controller, we’ll explore our first view.
1.3 Our first view
Recall that the ASP.NET MVC Framework uses a convention for locating views. The
convention is to find a .aspx file in a directory tree that matches /Views/controller-
name/actionname.aspx. In our next example, we’ll modify our controller by calling a
method on the Controller base class called View(). We’ll set the model, which is a
string with the text “Hello World”, to an entry in the ViewDataDictionary object on
the ViewData property of the Controller base class. This ViewDataDictionary
instance will be forwarded to the view. Although ViewData is a ViewDataDictionary
we recommend you depend only on the IDictionary<string, object> interface if
you’re replacing the view engine. View engines will be discussed in more detail in
chapter 4. In listing 1.9, we see that our action returns ActionResult instead of
string. After an action method returns, the ActionResult executes to perform the
appropriate behavior, which is rendering a view in this case. Examine listing 1.9 for
the current implementation of our controller. ViewData contains the object that will
be forwarded on to the view. The View() method also supports passing a single object
to the view that is then accessible via ViewData.Model, which we’ll explore later.
using System.Web.Mvc;
namespace MvcApplication.Controllers
{
public class HelloWorld3Controller : Controller
{
public ActionResult Index()
{
ViewData.Add("text", "Hello World3");
return View();
}
}
}
If you’re following along with this example, you’ll
want to create a HelloWorld3 folder inside
/Views in your project as shown in figure 1.8.
Next, add a view to the project inside /Views/
Helloworld3. You can use the New Item dialog
for the project and select the MVC View Page; a
quicker way is to use the context menu (right
click) off of the action and select Add View… as
shown in figure 1.9. This tool will create a view
with the proper name inside the proper folder.
Your project should now look similar to fig-
ure 1.8. Our new view, Index.aspx, resides in the
HelloWorld3 folder.
Listing 1.9 Using a view to render the model
Add objects
to ViewData
Figure 1.8 The proper location of
the HelloWorld3 folder is inside
the /Views folder. The default view
factory uses this convention. You can
override this behavior if you wish.
Other documents randomly have
different content
Olaf’s Grievances.
scandalize simple folk by the impudence which leads them to aim at
the abolition of the ancient usages of the Church; and I think further
that they have cherished the purpose of giving a lesson to me and
my government.’[477]
The prince, far from taking a lesson from
another, gave one, and that sharply, to the first preacher of the
capital.
These two men were both of a noble nature. In each were
greatness, devotedness, activity, and a strong love of good. But each
had also a fault which laid them open to the risk of a rude collision
with each other; and one shock of this kind might overthrow the
weaker. Gustavus would dictate as law whatever seemed to him
good and wise, and he did not intend to allow any resistance. He
placed great confidence in any man who showed himself worthy of
it; and of this he had given striking proofs to the two brothers Petri.
He did not easily withdraw his favor; but once withdrawn, it was
impossible to regain it.
Olaf, on his side, endowed with a spirit of
integrity and with a sincere and living faith,
had a vivacity of temperament which prevented him from pondering
the path of his feet. He could not endure contradiction, he could
hardly forget an offence, and he was too prone to attribute
malevolent motives to his adversaries. He not only believed that the
king intended to destroy the liberty of the Church (which was the
fact), but also that his obstinate maintenance of Romish customs
among the people would throw them back again into the Romish
apostasy. He began loudly to complain of Gustavus. He said to all
about him that the king was completely changed, and certainly for
the worse. He did not refrain from speaking in this manner even in
the presence of flatterers of Gustavus. The enemies of the reformer
hastened to take advantage of this. They reported to the king what
they had heard Olaf say, adding to it exaggerations of their own
invention.[478]
Their one object was to stir up hatred, and that
implacable, between the king and the reformer. They did not gain
their end at the first stroke; but a change was gradually wrought in
the relations between these two men, both so necessary to Sweden.
The king manifested to Olaf his unconcern by his manner and his
words. He saw him much less frequently; and when he did send for
him, there was a reserve in his reception which struck the reformer.
Frequently when Olaf requested to see the king, the latter refused to
admit him; or if he did receive him, business was despatched as
speedily as possible, as if his only care was to get rid of him. This
coolness, while it greatly grieved the sincere friends of the Gospel,
rejoiced its adversaries; and on both sides the people were
wondering, some with a sense of alarm, others with secret but deep
joy, whether Gustavus in thus gradually estranging himself from the
reformer was not at the same time making friends with the pope,
and whether a few steps more would not precipitate him into the
abyss.
Olaf himself, who while complaining of Gustavus had nevertheless up
to this time entertained no doubt of his good intentions, now took
offence, and resolved to avail himself of his rights as a minister of
the Word of God. Ought he to conceal the truth because it was to a
prince that it must be spoken? Did not Elijah rebuke Ahab, and John
the Baptist Herod? The feeling which blinded him did not allow him
to apprehend the important difference existing between a Gustavus
and an Ahab. An obvious fault of the king had often struck him. The
habit of swearing in a fit of anger was very common at the court and
in the town, and Gustavus set the example. Olaf, pained to hear the
name of God thus taken in vain, preached against the sin. He did not
hesitate, at the close of his sermon, to designate the king as setting
the example of swearing. He even had his discourse printed; and
letting loose his displeasure, he complained loudly of the obstacles
which the king placed in the way of a thorough reformation. The
young pastors, encouraged by the example of their chief, went
further than he did. They complained of the commands which the
king had given them, and gave free vent to their indignation against
a despotism which was, in their view, an attempt to violate the
rights of the Word of God and of Christian freedom.
It was a serious matter, and Gustavus was much moved by it. He
resolved to appeal to the archbishop. The primate, more temperate
The Mock Suns.
than his brother, confined himself to the duties of his calling. He was
never seen either in places of amusement or at the court, which his
predecessors used frequently to visit; but he was always at work in
his diocese. In consequence of the death of the queen, he had gone
at the king’s call to Stockholm, to marry him to his second wife, and
had immediately returned to Upsala to devote himself to his work.
Gustavus esteemed Lawrence; but he was, nevertheless, somewhat
out of temper with him, because he knew that at bottom he shared
his brother’s sentiments. To him, in his capacity of archbishop, the
king addressed his mandate, in September, 1539. ‘We had expected
of you and of your brother,’ said Gustavus, ‘more moderation and
more assistance in matters of religion. True, I do not know how a
sermon ought to be composed, but still I will tell you that preachers
ought to confine themselves to setting forth the essence of religion
without setting themselves up against ancient customs. You wrote
me word that sermons were being preached at Upsala on brotherly
love, on the life acceptable to God, on patience in affliction, and on
other Christian virtues. Very good: see to it that similar sermons are
preached throughout the kingdom. Christ and Paul taught obedience
to the higher powers; but from the pulpits of Sweden are too often
heard declamations against tyranny, and insulting language against
the authorities. I am accused, abuses which are complained of are
imputed to me, and these insults are published by the press. Holy
Scripture teaches us that a minister ought to exhort his hearers to
seek after sanctification. If people had any real grounds of complaint
against my government, why not make them known to me privately
instead of publishing them before the whole congregation?‘[479]
This letter, addressed to the archbishop of
Upsala, instead of soothing the Stockholm
minister, irritated him and inflamed still more his ardent zeal. A
circumstance which had little connection with the religious interests
of Sweden, convinced him that the time was come to denounce the
judgments of God. Olaf, in common with some of the most
enlightened men of his time, among others Melanchthon, believed in
astrological predictions. Seven or eight mock suns, reflecting in the
clouds the image of the sun, appeared over Stockholm at this time.
The sun was of course Gustavus, and the mock suns were so many
pretenders who were on the point of appearing around the king, one
or other of whom would take his place. ‘It is a token of God’s anger
and of the chastisement which is at hand,’ exclaimed Olaf in his
pulpit. ‘Punishment must come, for the powers that be have fallen
into error.’ The unfortunate Olaf did more. Exasperated by the part
which the king was taking in the government of the Church, he
caused these mock suns to be painted on a canvas, and this he hung
up in the church, in order that all might satisfy themselves that God
condemned the government and that His judgments were near.[480]
This proceeding was even more ridiculous than blameworthy, but it
was both. It took place, undoubtedly, after the king in his capacity of
Summus Episcopus had addressed the letter to the archbishop; for
although he spoke in it of the sermons on swearing, there is no
reference to that on the mock suns, which was, moreover, by far the
most serious affair.
The anger of Gustavus against Olaf was now at its height. His
enemies gladly seized the weapon with which by his mistakes he
furnished them against himself; and already they insulted him with
their looks. A storm was gathering against the reformer; and
Anderson, whose elevation and influence had made many jealous,
was to fall with his friend. These two personages being manifestly in
disgrace, the number of those who contributed to their ruin was
daily increasing; and it seemed as though nothing short of the death
of the objects of their hatred could satisfy them.
All this would have been without effect if Gustavus had continued to
protect the liberty of the reformers. But he thought (this is at least
our opinion) that he might take advantage of the animosity existing
between the two parties for maintaining his own universal and
absolute authority. Olaf was blinded by excess of zeal, and Anderson
did not sufficiently subordinate the interests of religion to those of
politics. A sharp lesson must be given to each of them. Olaf was
accused of having delivered seditious sermons, and of having
Charges Against
Olaf And Anderson.
censured in a historical work the ancestors of the king. This was not
enough.
Some still more serious charge must be
made. For this they went back four years
(1536), and it was given out that the project, formed by the German
inhabitants of Stockholm, of favoring the attack by the Hanse Towns,
had been confided to Olaf under the seal of confession—this
institution was still in existence—and that he had not made it known.
Even if this supposition had any foundation, was it not truer still that
the hostility of the Germans was universally known, and especially
by the vigilant Gustavus? But, in fact, there was little more in the
case than rumors, no attempt whatever at execution of the plan
having ever been made. To suppose that Olaf had intended to injure
the king, his own benefactor and the saviour of Sweden, is a
senseless hypothesis. Many other persons in Stockholm had learnt as
much of the matter and more than he had. But the enemies of the
Reformation wanted to get rid of the reformer; they must have some
pretext, and this appeared to be sufficient. People asked, indeed,
why Olaf had not been prosecuted for this offence four years before,
and why since that time no inquiry had been set on foot about it.
But all improbabilities were passed over. All the passions of men
combined against Olaf. Men of lower degree felt the hatred of envy
caused by the elevation of the son of the ironmaster of Orebro. The
great felt the hatred of pride, a hatred which is seldom appeased.
Worldly and bad men, such as were not wanting at the court, felt
that irreconcilable hatred which is cherished against those who
declare war on vice and worldliness. The king commanded that Olaf
as well as Anderson should be brought to trial. The writer who
recounts, in a not very authentic manner, the alleged offence of the
reformers, was a zealous Roman Catholic, and besides this a very
credulous man.[481]
The archives of Lübeck, the town which played
the leading part in the attack of which it was alleged that Olaf was
an accomplice, are very complete for the history of this period; but
they do not contain the slightest trace of any proceeding of the kind.
[482]
Men of peremptory character resemble each other; and,
although Gustavus Vasa was infinitely superior to Henry VIII., the
proceedings against Olaf and Anderson remind us of those instituted
by the king of England against his wives, his most devoted ministers,
and his best friends. The same court influences, and the same
pliability on the part of the judges were found in both cases; and, by
a stroke which recalled the Tudor sovereign, the king insisted that
the archbishop should sit as a judge at the trial of his brother. Olaf
and Anderson were condemned to death in the spring of 1540. This
was paying rather dear for the folly of the mock suns. ‘Simplicity,’ it
is said, ‘is better than jesting’; and a simple and credulous
proceeding often disarms the man who has a right to complain of it.
Olaf had been simple and credulous, but his foolishness did not
disarm the king.
The sentence which filled the ultramontanes with joy threw
consternation among the evangelical Christians, and especially
among the parishioners of Olaf. The man who had so often consoled
and exhorted them was to be smitten like a criminal. They could not
bear to think of it. They remembered all the services which he had
rendered them, and, what does not often happen in this world, they
were grateful. They therefore bestirred themselves, interceded in
behalf of their pastor, and offered to pay a ransom for his life. The
king did not push matters to extremities, but granted a pardon.
Perhaps his only intention had been to inspire fear in those who
assumed to set limits to his power. The townsmen of Stockholm paid
for their pastor fifty Hungarian florins. Anderson also saved his life,
but by a payment out of his own purse. These pecuniary penalties
contributed to keep people in mind that the king was not to be
contradicted.
The exaction of these sums for the ransom from the scaffold of the
two men who had done the most good to Sweden did no honor to
Gustavus. But he appears to have thought that strong measures
were necessary for the purpose of maintaining himself on the throne
to which he had been elevated. It was part of his system to strike
and to strike hard.
Olaf’s Sermon. Olaf subsequently resumed his functions as
preacher at the cathedral. Was not the
permission to reappear in the pulpit an acknowledgment of his
innocence? On this occasion he delivered an affecting discourse by
which the whole congregation was moved. He understood the lesson
which Gustavus had given him, and acknowledged that henceforth
resistance to the king’s authority in the church was useless. This
resistance might sometimes have been not very intelligent, but it
was always sincere and well meant. He could not begin again either
to preach the Gospel or to reform Sweden unless he submitted. This,
therefore, he did. Before every thing the Gospel must advance. The
king did not conceal his intention of governing the Church as well as
the State. He said to his subjects, ‘Take care of your houses, your
fields, your pastures, your wives and your children, but set no
bounds to our authority either in the government or in religion.[483]
It
belongs to us on the part of God, according to the principles of
justice and all the laws of nature, as a Christian king to give you
rules and commandments; so that if you do not wish to suffer our
chastisement and our wrath, you must obey our royal commands in
things spiritual as well as in things temporal.’ Olaf had learnt by
experience that the wrath of a king is as the roaring of a lion. He
had paid his debt to the liberty of the church. Henceforth he bowed
his head; he gave himself wholly up to his ministry; to instruct, to
console, to confirm, to guide, these tasks were his life, and in the
discharge of his duty he won high esteem. As for Anderson, he
never recovered from the blow which had fallen upon him. This fine
genius was extinguished. He who had done so much towards giving
a durable life to the church and to the State went slowly down to the
grave, overwhelmed with sorrow. A strange drama, in which the
actors, all in the main honest, all friends of justice, were carried
away by diverse passions, the passion for power and the passion for
liberty, and inflicted on each other terrible blows, instead of
advancing together in peace towards the goal which both alike had
in view.
George Normann.
Gustavus had won the victory. Olaf was not the only one who gave
way. The blow which had fallen upon Olaf alarmed the other
evangelical ministers so much that they abandoned the thought of
taking any part in the control of the church, and left it all to the king.
This pope was satisfied. The mock suns had disappeared one after
another, and the sun left alone shone out in all his glory.
Gustavus, having thus broken down what
threatened to be an obstacle in his way,
took up his position as absolute monarch in the Church and in the
State. In 1540 he obtained at Orebro a declaration that the throne
should be hereditary; and taking in hand the ecclesiastical
government he named a council of religion under the presidency of
his superintendent-general, who was strictly speaking minister of
worship. The king had engaged, as governor to his sons, George
Normann, a Pomeranian gentleman, who had studied successfully at
Wittenberg, and had come into Sweden with testimonials from
Luther and Melanchthon. ‘He is a man of holy life,’ Luther had
written to Gustavus Vasa, ‘modest, sincere, and learned, thoroughly
competent to be tutor to a king’s son.[484]
I recommend him cordially
to your majesty.’ Luther, however, aimed at more than the education
of the prince royal. Having had an opportunity of conversing with an
envoy of the king, Nicholas, a master of arts, he wrote to Gustavus
—‘May Christ, who has begun his work by your royal majesty, deign
greatly to extend it, so that throughout your kingdom,[485]
and
especially in the cathedral churches, schools may be established for
training young men for the evangelical ministry. Herein consists the
highest duty of kings who, while engaged in political government,
are friendly to Christian piety. In this respect your majesty has the
reputation of surpassing all others, illustrious king! and we pray the
Lord to govern by his spirit the heart of your majesty.’ Along with
George Normann, Luther sent a young scholar, named Michael
Agricola, whose learning, genius, and moral character he extols. In
conclusion he says—‘I pray that Christ himself may bring forth much
fruit by means of these two men; for it is he who through your
majesty calls them and assigns them their duties. May the Father of
mercies abundantly bless, by his Holy Spirit, all the designs and all
the works of your royal majesty.’[486]
It seems as if Luther had some
fear that Gustavus might monopolize too much the government of
the Church. In his view it is Christ who governs it, who calls and
appoints his laborers.
Gustavus appreciated the abilities and the character of Normann,
and saw in him an honorable but yielding man, at whose hands he
would not encounter the resistance which Olaf had offered. The
bishops gave him some uneasiness, and as he did not venture to
suppress them, he resolved to neutralize their influence by placing
the protégé of the Wittenberg reformer above all the clergy,
including the bishops and even the archbishop. While allowing the
episcopal order to subsist for form’s sake, he at the same time
introduced a semblance of the presbyterian order. In 1540 he
appointed in all the provinces conservators, counsellors of religion,
and seniors or elders who under the presidency of the
superintendent were to administer ecclesiastical affairs and make
regular visitations in the dioceses. No change might be made or
even proposed in the Church without the express permission of the
king. The opposition of Olaf and other ministers to certain remains
of popery was not, however, without effect. Gustavus abolished
them. But this semi-episcopal and semi-presbyterian constitution
could never be got to work perfectly; and at a later time fortunate
circumstances restored to the Swedish Church a more independent
standing. Gustavus continued to have at heart the serious fulfilment
of the functions of supreme bishop. He made laws for the
frequenting of the religious assemblies, for the observance of the
rules prescribing a decorous behavior in the church, for the
suppression of immorality both among the laity and among the
ecclesiastics, for the improvement of teaching and for the spread of
civilization and culture among the people. Desirous of seeing the
extension of the kingdom of God, he sent missionaries into Lapland.
In Sweden likewise he set the inspired Word above every thing.
‘Thou doest well,’ he wrote to one of his sons, ‘to read the writings
of the ancients and to see how the world was then governed; but do
Excuses For
Severity.
not give these the preference over the Word of God. In this is found
true instruction and reasonable morals; and from it we learn the best
mode of governing.’
This zeal for good did not prevent him from
hitting hard when he thought he saw any
thing amiss. He could be calm, gentle, and tolerant, but also
earnest, terrible, and swift as a thunderbolt. If he perceived any
opposition he struck energetically. ‘It is not right,’ he said one day,
‘that the bishop of Strengnaes should dwell in a stone house. It
appears to me that a wooden house might suffice for a servant of
him who made himself poor.’ The bishop boldly answered—‘It is
doubtless in the same chapter of Holy Scripture that it is said that to
the king tithe ought to be paid.’ The bishop’s reply having offended
the king, he was not slow to show his displeasure. The marriage of
the bishop was at this time being celebrated. It was his wedding-
day, and there was a large company and a grand feast in the stone
house. Gustavus unhesitatingly sent his sergeants in the very midst
of the rejoicings, with orders to carry off the bishop from the
marriage table, paying no regard to the general alarm, and he cast
him into prison. His benefice was given to another. The
contemporaries of Gustavus might reproach him, and with good
reason, for his severity; and yet this seems moderation in
comparison with the ways of Henry VIII., Mary Tudor, Francis I.,
Henry II., Charles IX., and with those of his predecessor Christian II.
‘I am called,’ he said, ‘a harsh monarch; but the days will come when
I shall be regretted.’[487]
He had indeed other qualities which made
people forget his severity. The beauty of his person predisposed men
in his favor, and the eloquence of his speech carried away all with
whom he had to do.
But there are other considerations which although they do not justify
his rigorous measures, explain them.
The kingdom of Christ not being of this world ought not to be
governed by kings and by their secretaries of state. This principle
once admitted, there are three remarks to make: The development
of Christian civilization was not sufficiently advanced in the sixteenth
century for a recognition of the independence of the two powers.
Catholicism was still so powerful in Sweden that nothing short of the
authority of such a king as Gustavus could secure to the Gospel and
to its disciples the liberty which they needed. Lastly, if Gustavus was
wrong in assuming, as so many other princes did, the episcopal
office in the Church, he did at least discharge its duties
conscientiously.
In 1537 the king had received deputies from the elector of Saxony,
the landgrave of Hesse, and the Protestant towns, who entreated
him to unite with the evangelical churches of Germany.[488]
Gustavus
had promised to do all that might be in his power for the good of
their confederation. In 1546 he was formally asked to enter into the
league of Smalcalde; but this he declined to do. The Confession of
Augsburg was not accepted in his lifetime. It was only after many
vicissitudes that Sweden was induced to place itself under this flag.
CHAPTER XI.
THE SONS OF GUSTAVUS VASA.
(1560-1593.)
The transformation effected by the Gospel in Sweden during the
reign of Gustavus Vasa was incomplete. The whole lump was not
leavened. Many of those who received the Reformation did not
understand it; and a very large number of Swedes had no wish for
it. This state of things, and the vexations which the king’s sons
caused him, saddened his old age. At the beginning of the year
1560, the king, feeling ill, convoked the Diet. It met on the 16th of
June, and he appeared and took his seat in it on the 25th, having
beside him his sons Erick, John, and Magnus, and on his knee his
youngest son Charles. He spoke, calling to mind the deliverance
which had been granted to Sweden forty years before; and this he
attributed to the help of God. ‘What was I that I should rise up
against a powerful ruler, king of three realms, and the ally of the
mighty emperor Charles the Fifth, and of the greatest princes of
Germany? Assuredly it was God’s doing. And now, when the toils and
pains of a troubled reign of forty years are bringing down my gray
hairs to the grave, I can say, with King David, that God took me
from the sheepcote and from following the sheep to be ruler over his
people.’ Tears stifled his voice. After a pause he resumed—‘I had
certainly no anticipation of so high an honor when I was wandering
about in the woods and on the mountains to escape from the sword
of my enemies who thirsted for my blood. But blessing and mercy
have been richly bestowed on me by the manifestation of the true
Word of God. May we never abandon it! I do not shrink, however,
from confessing my faults. I entreat my faithful subjects to pardon
the weakness and the failures which have been observed in my
Retirement Of
Gustavus.
reign. I know that many persons think that I have been a harsh
ruler; but the days are coming in which the sons of Sweden would
gladly raise me out of the dust if they could.[489]
‘I feel that I have now but a short time to
live; and for this reason I am about to have
my will read to you; for I have good reasons for desiring that you
should approve it.’ The will was then read, the Diet approved it, and
swore that it should be carried out. Then Gustavus rose and thanked
the States for making him the founder of the royal house. He
resigned the government to his son Erick, exhorted his sons to
concord, and stretching out his hand towards the assembly, gave it
his blessing, and thus took leave of his people.
On the 14th of August Gustavus took to his bed, which he was no
more to leave till his death. He said—‘I have been too much
occupied with the cares of this world. With all my wealth I could not
now buy a remedy which would save my life.’ One of those about
him, anxious to know what pain he felt, said to him; using a German
mode of speech—‘What do you want?’ He replied—‘The kingdom of
heaven, which thou canst not give me.’ His chaplain, in whom he
had no great confidence, suggested to him that he should confess
his sins. Gustavus, who had confessed them to God as well as to his
people, but who had a horror of confession to a priest, replied
unceremoniously and indignantly—‘Thinkest thou that I shall confess
my sins to thee?’ A little while after, he said to those about him—‘I
forgive my enemies, and if I have wronged any man, I pray him to
forgive me. I ask this of all.’ He then added—‘Live all of you in
concord and in peace.’ During the first three weeks he spoke in a
remarkable manner about things temporal and things spiritual.
During the last three he kept silence, and was frequently seen
raising his hands as if in prayer. After making a profession of his
faith, he received the communion of the body and the blood of the
Saviour. His son John, who was present, and was the cause of his
anxious forebodings, which were too soon realized, having heard the
confession of his father, exclaimed—‘I swear to abide by it faithfully.’
The king made a sign for paper to be given him, and he wrote
The Two Sons Of
Gustavus.
—‘Once professed never to be retracted, or a hundred times
repeated to....’ His trembling hand could not finish the sentence.
After this he remained motionless. The chaplain having begun again
his exhortations, one of those in attendance said—‘You speak in
vain; His Majesty hears no longer.’ Then the chaplain leaned towards
the dying man, and asked him whether his trust was in Jesus Christ,
and entreated him, if he heard, to make some sign. To the
astonishment of all, the king with a clear voice answered, ‘Yes.’ He
then breathed his last. It was eight o’clock in the morning of
September 29, 1560.[490]
Erick, his eldest son, who was heir to the
crown, had hitherto appeared little worthy
to wear it. In his character were united the eccentric disposition of
his mother,[491]
the princess of Saxe-Lauenberg, and his father’s
passion. He was rash and presumptuous; and when Gustavus spoke
to him by way of exhortation or rebuke he was angry. Gustavus,
deeply mourning over him, wrote one day to him—‘For the sake of
the sufferings of the Son of God, put an end to this martyrdom
which thy aged father endures on thy account.’[492]
In his sports he
was singular and even cruel. Erick and John, the latter the eldest son
of the second wife, were constantly at variance, at first about their
games, then about their fiefs, and at last about the crown. Every
body knew that the younger of the two brothers was ambitious of
the birthright of the elder, and thought that he was entitled to the
realm. The father was weighed down with grief on account of these
two sons.
Erick had not been left without good counsel. A French Protestant,
named Denis Burrey (Beurreus), a zealous Calvinist, had succeeded
Normann as his governor. In addition to Burrey, another Frenchman,
Charles de Mornay, baron of Varennes, was well received at his
court. The two Calvinists persuaded Erick to ask for the hand of the
Princess Elizabeth, even before she became Queen of England.[493]
Duke John exerted all his influence to promote this plan, which, in
case it succeeded, might leave to him the crown of Sweden.
Disputes About The
Supper.
Magnificent embassies were sent; John and Erick himself went to
England, but the princess never gave him any hope.
At the time of the prince’s accession to the throne, the people had
some hope of him. The germ at least of great qualities was in him;
and his understanding, which was above the average, had been
developed by the care of his teachers. He was well acquainted with
literature, with mathematics, philosophy, and foreign languages.[494]
His figure was well formed; he was a good rider, a good swimmer, a
good dancer, and a good soldier. He spoke pleasantly and was
agreeable in his intercourse with others. But in the depth of his
nature was a temper strange, distrustful, suspicious, and fierce,
which might on a sudden display itself in outward acts calculated to
excite at once both pity and horror.
Burrey, who had been appointed to instruct the prince in letters and
in science, was not entrusted with the department of religion. This
belonged to the archbishop, Lawrence Petersen, and to the Lutheran
ministers named by him. Erick was to be a good Lutheran; but the
French Protestant, convinced of the truth of Calvin’s principles, made
them known to his pupil. Calvin himself, doubtless through the
medium of Burrey, was in correspondence with Gustavus in 1560,
towards the close of the king’s life.
In Sweden the Calvinists gave especial
prominence to the doctrine of the Lord’s
Supper. Burrey, who appears to have apprehended the doctrine in
the way of logic rather than of spiritual insight, maintained it by
syllogisms. He said—‘All who eat the flesh of Christ and drink his
blood have eternal life. Now the ungodly have not eternal life.
Therefore the ungodly do not eat the flesh of Christ.’[495]
The Apostle
John says nothing about the corporeal mastication, it but speaks
only of the spiritual. Therefore, he recognizes no other mastication
but that which is by faith. Christ gives his body and his blood only to
those who show forth his death. But the ungodly do not show forth.
Therefore he does not give it to them. The Frenchman maintained
these doctrines in a Latin work. He had of course a right to do so;
but he had no right to attack as he did the archbishop, brother of
Olaf, a zealous defender of the Lutherans, or to allege either in
conversation or in his writings that the prelate was a papist. The true
Protestants, and foremost among them Zwinglius and Calvin,
generally expressed great respect for Luther and for all his disciples,
acknowledging them as brethren in the faith. But the sectarian spirit,
unfortunately, was beginning now to take the place of the Christian
spirit.
The influence of the French Protestants, however, made itself felt in
other respects and in a wholesome way. Erick, shortly after his
accession to the throne, abolished the festival days which were
connected with a superstitious system, and the Catholic rites which
had been retained in the divine service. He went farther, and made it
everywhere known that his kingdom was a free state, open to all
persecuted Protestants. Many Protestants, therefore, especially
French, came to Stockholm and were kindly received by the king,
becoming even particular objects of his favor. This gave rise to
jealousies and suspicions. The question was raised whether the king
was not a Calvinist in disguise. Wine having become scarce in
Sweden, in consequence of the obstacles thrown in the way of the
trade by Denmark, it was asked whether it would not be permissible
to make use of some other fluid at the Lord’s supper. The
Frenchman, Burrey, held the opinion that it would, and this
increased the grief of good Lutherans. The archbishop especially
declared himself strongly and with good reason against this fantastic
proposal, and published a Latin work on the subject.[496]
These controversies gave rise to much agitation in Sweden; but they
were superseded by troubles of a graver kind. Duke John, Erick’s
younger brother, having put forward claims which Erick would not
satisfy, and having even caused the king’s envoys to be arrested,
and invited the inhabitants of Finland to take an oath of fealty to him
and to defend him, was made prisoner on the 12th of August, 1563.
[497]
A rumor was afterwards current of a conspiracy of the Sture
family, who had exercised, before the reign of Gustavus, the royal
power as administrators of the kingdom. Their intention, it was said,
was to overthrow the house of Vasa and restore the hereditary
kingdom to their own family. Erick having met in the street a servant
of Svante Sture carrying a gun, this unfortunate man was sentenced
to death at the beginning of January, 1567, and several of the Stures
and of their friends were thrown into prison. With this incident
began the great misfortunes of the prince. Infelicissimus annus Erici
regis, he said, speaking of this year in his journal.
Madness Of Erick. On May 24 Svante Sture and another of the
prisoners had asked pardon of the king and
had received a promise of early liberation. In the evening, as the
king was walking with Caroli, ordinary (or bishop) of Calmar, some
one ran up and told him that his brother, Duke John, had made his
escape and had raised the standard of rebellion. In a state of great
excitement, he returned to his castle. His mind wandered; he fancied
that every one was a conspirator; he saw himself already hurled
from the throne; and, beside himself, he went, dagger in hand, into
the room in which Nils Sture was confined.[498]
He rushed upon the
unhappy man and pierced him in the arm; one of his guards gave
the fatal stroke. At this moment the prison of the father of Nils Sture
opened, and the king, overpowered at the sight, fell at his feet and
cried—‘For God’s sake pardon me the wrong that I have done you!’
The old man, who did not know what he meant, answered—‘If any
thing should happen to my son, you are responsible to me before
God.’ ‘Ah,’ said the king, whose thoughts were wandering more and
more, ‘you will never pardon me, and for this reason you must share
the same fate.’ He then fled precipitately, as if the castle were full of
assassins and every prisoner loaded with chains were pointing a
dagger at him. He took the road to Floetsund, attended by some
guards; and in a little while one of these returned with an order to
put to death all the prisoners in the castle ‘except Sten.’ Two of them
bore this name, and considering the uncertainty, both of them
escaped, but the rest perished. Ere long the unhappy Erick was
seized with horror at the thought of his crime. He believed himself
pursued by the ghost of Nils Sture, whom he had slain. Filled with
distress and remorse he plunged into the forest. Burrey, who had left
the castle at the moment when the order to execute the prisoners
arrived, immediately set out in the track of the prince, whom he
desired to recall to his senses, and from whom he intended to
obtain, if possible, the revocation of the cruel order. He at length
came up with him in the middle of the wood; but the raving man
fancied that his old teacher had shared in the conspiracy of those
whose lives he wished to save. A prey to the most violent madness,
he gave an order to one of his guards, and the Frenchman whom he
had loved so well, to whom he owed so much, fell at his feet,
pierced through and through.[499]
The unhappy man then got away
from his guards, who were still accompanying him, and fled alone.
He threw away his kingly apparel, and wandered about in the
woods, in the fields, and in the loneliest places, with a gloomy air,
wild eyes, and fierce aspect. No one knew where he was. Like the
king of Babylon, he went up and down in the land afar from the
haunts of men; his dwelling was with the beasts of the field, and his
body was wet with the dew of heaven. At length, on the third day
after the murder, he made his appearance in the garb of a peasant
in a village of the parish of Odensala; and presently several of his
men who were in search of him ran up to him. ‘No, no,’ said he on
receiving the acknowledgments of those who respectfully saluted
him, ‘I am not king.’[500]
‘It is Nils Sture,’ he added, ‘who is
administrator of the kingdom.’ This was the man that he had
assassinated. They endeavored in vain to pacify him. ‘Like Nero,’ he
exclaimed, ‘I have slain my preceptor.’ He would neither eat nor
sleep; all entreaties were fruitless. At last Catherine Maenstochter, to
whom he had been strongly attached and who soon became his
consort, succeeded in persuading him. He now became more calm
and allowed them to take him to Upsala. On June 3 he was taken
back to Stockholm. He was in a state of great agitation when he
entered the town; his heart rent with remorse, his eyes and his
hands raised to heaven. It was a long time before he entirely
recovered his reason.
Negotiations were set on foot between Duke John and the unhappy
king. The former requested an interview with his brother, and this
took place on October 9 at Wantholm, or, according to some
authorities, at Knappforssen, in Wermeland.[501]
The brothers met
under an oak tree, which is still called the King’s Oak. They had a
second interview shortly after at Swarhjo. Erick, who was perpetually
haunted by the thought that the murders which he had ordered had
deprived him of the crown, fell at his brother’s feet and hailed him
king. From this time he considered himself a dependent on his
His Treatment In
Prison.
brother and spoke sometimes as if he were king and sometimes as if
he were a captive. He appeared, at the beginning of 1569, before
the States assembled as a high court of justice, and there
energetically defended himself, sparing no one, and least of all, the
nobility. When John interrupted him by telling him that he was out of
his mind, he replied, ‘I have only once been out of my mind, and
that was when I released thee from prison.’ He was deprived of the
crown on the ground that he had lost his reason, and was sentenced
to perpetual confinement, but with royal treatment.
Duke John had now reached the summit of
his ambition. He set himself to win over
adherents, so that no one might be tempted to call to mind the fact
that his throne was usurped. He was amiable and obliging alike to
the nobles, the ecclesiastics, and the people; and the popularity
which he enjoyed seemed daily to increase. ‘Certainly,’ people said,
‘he means loyally to carry out the will of his father.’[502]
But the joy
and the popularity did not last long. It was soon perceived that he
was giving full play to his hatred of Erick, whom he called his most
deadly enemy. He spared his life, indeed, at the entreaty of the
queen, widow of the late king, but he made him suffer all the
horrors of the most rigorous imprisonment. The unhappy prince had
to endure in his own body shameful treatment at the hands of his
keepers and of those whom he had displeased in the course of his
reign. One day a man more mad and more cruel than himself, Olaf
Gustavsson, had a violent altercation with him in the prison, and left
him lying in his blood. ‘God knows,’ wrote Erick to his brother John
(March 1, 1569), ‘what inhuman tortures I am forced to endure—
hunger and cold, infection and darkness, blows and wounds. Deliver
me from this misery by banishment. The world is surely large
enough to allow of the hatred between brothers being mitigated by
the distance of places and of countries.’[503]
But nothing could
appease his enemy, his brother. At first he had allowed him to see
his wife and his children, which was a great pleasure to the unhappy
man; but this consolation was afterwards refused him. They gave
him neither paper nor ink, and in the long hours of his captivity he
used to write with water blackened with charcoal on the margins of
the books which he was permitted to read. On these he left, in
particular, an eloquent defence of his cause.
Other motives also came into action to destroy the premature
popularity of John III. With the life of Burrey and the prison of Erick
the Calvinistic period in Sweden was over; with the accession of the
new king the popish period began. Sweden presented at this time an
example of the manner in which Rome proceeds to bring back to her
feet a people that had departed from her. John took delight in the
pomp of the Romish worship, and his wife, a Polish princess, was a
decided and zealous Roman Catholic. Although she did not belong to
that fanatical, barren, and superstitious ultramontanism which is not
even a religion, she firmly believed that outside the pale of her own
Church there was no salvation. But her faith was sincere. She had no
wish that conversions should be effected by force; nevertheless she
was convinced that the best of all good works was to extend as
widely as possible the domain of the pope. She had for her
confessor a Jesuit, named John Herbest; and the work of darkness,
of which this man was one of the principal agents, was carried on in
a Jesuitical manner. The king began by listening without objection to
the assertions of his courtiers that a moderate Catholicism, a middle
stand-point between Popery and Lutheranism, would be the best
religion. John thought so. He consequently published in 1571 an
ordinance purporting that as Anschar had in the ninth century
introduced true Christianity, they must abide by it, and must preach
good works, as giving salvation equally with faith. At the same time
exorcism at baptism, tapers on the altar, the sign of the cross, the
elevation of the host, and the multiplicity of altars were re-
established. The archbishop, Lawrence Petersen, offered no
opposition to this ordinance, either from weakness of age or of
character, from dread of Calvinism, or from fear of the king. His
brother Olaf would have been more vigilant and more steadfast.
Further steps were soon taken. The queen, at the suggestion of
Cardinal Hosius, implored the king to re-establish the dignity of the
priest and the sacrifice of the mass.[504]
On the death of the
Romanism In The
Ascendent.
archbishop, in 1573, John III. named as his successor Lawrence
Gothus, a man who being always willing to yield could not fail to be
an excellent instrument for the accomplishment of the purposes of
Rome. The king caused to be drawn up seventeen articles, which
sanctioned the intercession of the saints, prayers for the dead, the
re-establishment of convents and of all the ancient ceremonies. The
archbishop signed them; and as soon as this pledge was obtained,
the ceremony of the consecration was performed with much pomp.
On this occasion reappeared the mitre, the episcopal staff, the great
cope called pluvial, and the holy oil for the
anointing of the prelate. Henceforth,
Catholicism was in the ascendent. John had his son Sigismund
brought up in the strictest Romanism, in the hope of thus opening
the way for him to the throne of Poland, which Cardinal Hosius had
promised him. Two Jesuits, Florentius Feyt and Lawrence Nicolaï,
sent by the famous society with which the king was in
correspondence, arrived at Stockholm in 1576, and gave themselves
out for Lutheran ministers. They ingratiated themselves amiably and
adroitly, says one of them, with the Germans, and this at first more
easily than with the Swedes.[505]
They paid visits to the pastors and
conversed with them on all manner of subjects for the purpose of
gaining them over. They spoke Latin with ease and elegance, so that
the good Swedish pastors, who were unlettered men, were filled
with admiration, and promised them their co-operation.[506]
Feyt, in a
college at Stockholm, newly founded by the king, and Nicolaï, at the
university of Upsala, spread out their nets, and by lectures, sermons,
disputations, and conversation, they succeeded in bringing back to
the abandoned faith now one and now another, thus drawing after
them a goodly number of souls.[507]
The cardinal lavished his instructions upon them. ‘Let them avoid
creating any scandal,’ he wrote to the Jesuit confessor of the queen;
‘let them extol faith to the skies; let them declare that works without
faith are profitless; let them preach Christ as the only mediator and
His sacrifice on the cross as the only sacrifice that saves.’[508]
The
main point was to get the Swedes to re-enter the Roman pale by
Proceedings Of The
Jesuits.
giving them to understand that nothing was preached there but the
doctrines of the Gospel. This once accomplished, some means would
certainly be found of again setting meritorious works by the side of
faith, the Virgin Mary by the side of Christ as intercessor, and the
sacrifice of the mass by the side of the sacrifice of Calvary. The king
commanded all the pastors to attend the
lectures of these Jesuits, passing
themselves off as Lutherans. These men quoted the writings of the
reformers, but at the same time confuted them, and endeavored to
show that they contradicted one another. The king was sometimes
present at these disputations, and even took part in them. He spoke
against the pope, and thus gave the foreign theologians a pretext for
making a clever apology for the Roman court. The reverend fathers,
moreover, were not particular. They gained over a secretary of the
king, named Johan Henrikson, who was living with a woman whose
husband he had killed. Father Lawrence, in the first instance, gave
absolution to these two wretched people; and afterwards a
dispensation to marry. This convert, after having again been an
accomplice in crimes, died from drunkenness. In a short time, other
Romish priests arrived in Sweden, and were placed in various
churches. At the instigation of these missionaries of the pope, many
young Swedes were sent abroad, to Rome, to Fulda, and to Olmutz,
to be educated there in Jesuit colleges at the expense of the state.
Many Roman Catholic books were translated, especially the
catechism of the Jesuit Canisius; and these were distributed in large
numbers among the people.[509]
Cardinal Hosius did not fail to write
to the queen that she should by no means be disheartened nor
slacken in her efforts to bring about the conversion of the king.[510]
At the same time he wrote to the king entreating him to become a
true Catholic. ‘If there be any scruple in your majesty’s mind,’ said
he, ‘there is nothing upon earth I desire more than with God’s help
to remove it.’[511]
The queen and her connections at length prevailed upon the king to
take one step towards the pope. Count Pontus de la Gardie set out
for Rome, with instructions to request the pontiff, on the part of
Fratricide.
John III., to appoint prayers to be made throughout the world for
the re-establishment of the Catholic religion in the North; to propose
his own return and that of his people into the Roman Church, upon
condition nevertheless that the ecclesiastical estates which were in
the hands of the king and of the nobles should remain there, that
the king should be acknowledged head of the Swedish Church, that
mass should be allowed to be said partly in Swedish, that the cup
should be received by the laity, and that marriage should be
permitted to the priests, although they ought to be exhorted to
celibacy. The court of Rome, without accepting these conditions, left
the negotiations open, in hope of getting more another time.[512]
The
king, desirous of giving the pontiff a mark of his zeal, caused to be
composed and printed, in 1576, under the direction of the Jesuits, a
new liturgy almost entirely Roman in character; and in the following
year he began to persecute those who refused to accept it. Cardinal
Hosius now gave thanks to God for the conversion of this prince
(October, 1577.)
This same prince, who now bowed down
his head under the yoke of the pope,
signalized this year (1577) by the perpetration of one of those
crimes which reveal an unnatural heart, a man devoid of feeling. His
unhappy brother, although now rendered completely powerless and
reduced to a state of the deepest wretchedness, gave him some
uneasiness. Among the people there had been movements in his
favor. Mornay had been accused of aiming at the restoration of Erick,
and on this charge had been put to death on August 21, 1574. It
had been openly said that it would be better for one man alone to
suffer than for so many to perish in his cause. In January, 1577, the
king wrote to Andersen of Bjurum, commander at Oerbyhus, to
which place the ex-king had been recently removed. Here is the
order given by a brother for the death of a brother; a document
such as is not to be found elsewhere in history. It appears that John
recollected his brother’s cleverness and energy, which qualities,
however, must surely have been diminished by his imprisonment. ‘In
case there should be any danger whatsoever, you are to give King
Erick a draught of opium or of mercury strong enough to ensure his
death within a few hours. If he should positively refuse to take it,
you are to have him bound to his seat and open veins in his hands
and feet till he die. If he should resist and render it impossible to
bind him, you are to place him by force upon his bed, and then
smother him with the mattress or with large cushions.’[513]
John III.,
however, did an act of mercy at the same time. He ordered that,
before putting his brother to death, a priest should be sent to the
Calvinist Erick, at whose hands he should receive the sacrament.
What tender concern for his salvation!
The secretary Henrikson, the man who had killed the husband of the
woman with whom he lived, consequently arrived at the castle of
Oerbyhus accompanied by a chamberlain and the surgeon-major
Philip Kern. The latter had prepared the poison, and the three men
brought it with them. On Sunday, February 22, the priest presented
himself to do his duty. After an interval of two days, the poison was
served up to the unfortunate prince in a soup. He took it quite
unsuspiciously and died in the night (two o’clock A.M.), February 26,
at the age of forty-four.[514]
The deposed king had certainly
committed a crime when he wounded with a dagger Nils Sture,
whose intention he believed was to snatch from him his crown. But
at the spectacle of this cold-blooded poisoning, directed in an
ordinance with such minute details, and effected in so cowardly a
manner, we feel the shudder of horror aroused by great crimes. John
then wrote to Duke Charles that their brother had died after a short
illness, of which he, the king, had been informed too late. Charles
understood what this meant, and he expressed his grief at the
unworthy manner in which King Erick had been buried. ‘He was
nevertheless,’ wrote Charles, ‘king of Sweden, crowned and
anointed; and whatever the evil into which he may have fallen,
which may God forgive him! in the course of his reign he did many
good deeds worthy of a brave man.’[515]
Swedish refugees in various
places lamented his tragic end, and even called upon France to
avenge it by placing his heir upon the throne.[516]
After Erick’s death, the fratricide king continued his progress towards
popery. The clever Jesuit, Antoine Possevin, who made his
appearance as envoy from the emperor, but who was in fact a legate
of the pope, arrived in Sweden, for the purpose of getting the king
and the kingdom to decide on making a frank submission to Rome.
[517]
The king had an interview with him in the convent of Wadstena,
and was formally but secretly received by this reverend father into
the communion of the Roman Church. While pardoning his sins, the
Jesuit imposed on him the penance of fasting every Wednesday,
because it was on this day that he had caused his brother to be
poisoned.[518]
The influence of this Jesuit was at the same time felt
throughout the Church. Orders were given to withdraw from the
psalms all the passages against the pope, to exclude Luther’s
catechism from the schools, and to submit to the canonical laws of
Rome, an extract from which was published. Martin Olaï, bishop of
Linkoping, having called the pope Antichrist, appeared publicly in the
cathedral, and before the altar was stripped of his pontifical
decorations. His diocese was given to Caroli, ordinary of Calmar, a
former courtling of Erick’s, a treacherous man, who had driven the
king to the murder of Sture. At the same time Jesuits were entering
the kingdom under various names and various dress; and believing
that the time for cautious proceedings was past, they preached
vigorously against evangelical doctrine, which they called heretical,
so that it began to be said among the common people that these
men could do nothing but curse and bark. The district entrusted to
the government of Duke Charles was the only one that was
protected from this Romish invasion.[519]
Suddenly the tide ceased flowing and seemed to turn back towards
the fountain-head. John III. had cast his eyes upon the duchies of
Bari and Rossano, in the kingdom of Naples, believing that his wife,
as the daughter of Bona Sforzei, had some title to them. But the
pope had taken a course opposed to his interests; and he had
likewise sacrificed Sweden in a treaty, which had been concluded
through his mediation, between Russia and Poland. At the same time
the principles of freedom which Protestantism had made current,
Death Of Queen
Catherine.
Assembly Of
Upsala.
especially in opposition to the lordship of the priestly class, had so
deeply entered into men’s minds that the practices, the artifices, and
the impudence of the Jesuits appeared revolting to the townsmen,
and were stirring up in the whole nation a spirit of resistance to the
encroachments of the papacy. At length, in
1583, Queen Catherine, who had been the
soul of the popish reaction, died; and the king having married again,
his second wife, Gunila, declared herself heartily against Rome.
At this time the tide, which ever rising had borne along with it into
Sweden the rites and the doctrines of Rome, was succeeded by the
ebb, which as it retired swept away successively every thing which
the rising waters had deposited on these northern shores. The
pastor of Stockholm, who had become a Catholic, was deprived; the
Jesuits were driven out of the kingdom, and the posts which they
held in the college of Stockholm were given to their adversaries.
Public opinion energetically declared itself against the adherents of
the pope; and the king, turning from one wrong course to another,
began to persecute them, although he still retained his liturgy. He
died in 1592, and his son Sigismund, a zealous papist, who, since
1587, had been king of Poland, now returning to Sweden, began to
oppress Protestantism. His uncle, Duke Charles of Sudermania, an
intelligent and enterprising prince, who was not only opposed to
popery, but had a leaning towards the Protestant side, put himself at
the head of this party. Sigismund was obliged to leave Sweden, and
Charles became first administrator of the kingdom and ultimately
king.[520]
Charles convoked at Upsala a general
assembly for the purpose of regulating the
state of the Church. On the 25th of February, 1593, he was there
present himself with his council, four bishops, more than three
hundred pastors, deputies from all parts of the kingdom, many
nobles, townsmen, and peasants. There was a young professor of
theology from Upsala, Nicolaus Bothniensis, who had distinguished
himself by his resistance to Romish institutions, and had even been
thrown into prison. The assembly, desirous of doing honor to his
fidelity, now named him its president. With one accord the assembly
declared that Holy Scripture interpreted by itself was the only basis
and the only source of evangelical doctrine. After this all the articles
of the Confession of Augsburg were read; and Peter Jona, who had
just been named bishop of Strengnaes, rose and said, ‘Let us all hold
fast this doctrine; and will you remain faithful to it even if it should
please God that you must suffer for so doing?’ All answered, ‘We are
prepared to sacrifice for its sake all that we possess in the world, our
property and our lives.’ Peter Jona then resuming his speech said,
‘Sweden is now become one man, and we all have one and the
same God.’[521]
All the changes in doctrine and in ritual which had been introduced
in the reign of John III. were abolished. The teaching of evangelical
doctrine was universally established. The assembly of Upsala was an
event the results of which were felt far and wide, beyond the limits
of Sweden. This was manifest when, at a later period, by the
services of Gustavus Adolphus, the Reformation was consolidated in
Europe.
BOOK XIII.
HUNGARY, POLAND, BOHEMIA, THE NETHERLANDS.
The Magyars.
CHAPTER I.
THE FIRST REFORMERS AND THE FIRST
PERSECUTORS IN HUNGARY.
(1518-1526.)
Few countries had so much need of the Reformation as Hungary.
When, in the year 1000, she abandoned paganism under King
Stephen, she attached herself to Rome, and Rome brought on her
two evils. She sent into the country large numbers of monks, priests,
prelates, primates, and legates; and these men led her—this was the
first evil—to a mere outward profession of Christianity, and
oppressed the various tribes who peopled the land—this was the
second evil. Further, the people, rather more than half a century
later, assembled at Alba-Royal, rose in revolt against the clergy. The
former were defeated, many were put to death, and the pope,
boasting of the victory, wrote to the king, bidding him remember
that henceforth the pope of Rome was his suzerain. Shortly before
the Reformation, in 1512, the Hungarian passion for independence
led them to revolt again. But at this time they were destitute of true
Christian principles, and the only result of the movement was to
cover their country with devastation, and deluge it with the blood of
sixty thousand of its sons. This heroic nation was once more thrown
into bondage. The light and the power of the Gospel were needed to
effect its regeneration, and to infuse strength into it for resisting its
two enemies, the Grand Turk and the pope.
If the tribes of Hungary were without a true
and living faith, they were nevertheless, the
Magyars especially, among the races best fitted to embrace the
Reformation. They were characterized by a noble independence of
spirit and a nature endowed with higher cravings. When some
Christian men proclaimed among them the grace of Jesus Christ,
they joyfully embraced the spiritual truths which Geneva was then
diffusing in Europe; and the liveliness of their faith, the morality of
their conduct, their love of freedom, and the prudence of their
character, soon rendered a glorious testimony to the Reformation.
But the cleverness and the violent persecuting spirit of the
Hungarian prelates and of the courts of Rome and Vienna contended
vigorously against the religious renovation of this people, drew them
back in part to the bosom of the Church, and prevented the spread
of evangelical doctrine into other districts of the country. The mighty
forces of the flesh engaged in a conflict with the mighty forces of the
spirit. The dominion of prejudice gained the ascendency over that of
truth. Faith, wisdom, virtue, originative energy, freedom—all were
crushed. God, however, by his power, kept for himself a people in
these lands; and a considerable part of the Hungarian nation
remained Protestant, but were constantly subject to the inspection
of priests and to oppression by the powerful.
Hungary, in common with the other countries of eastern Europe, had
received, before the Reformation of the sixteenth century and while
it was still in subjection to Rome, some rays of light which here and
there illumined it. Some of the Vaudois had sought refuge there; the
doctrine of John Hus had been spread in the land; some of the
brethren banished from Bohemia had built churches there, and had
acquired great influence.
In 1521 two young people, children almost, the hope of Hungary,
were united before the altar. The husband was Louis II., a son of
King Ladislaus, who had ascended the throne in 1510, at the age of
ten. The young prince, who was amiable, but easy tempered, weak,
and addicted to pleasure, was not capable of preventing the
prevalence of disorder in the kingdom at the time the Turks were
threatening it with their terrible invasions. He had little courage, a
quality which was common enough among his fellow-countrymen;
he was obstinate, and yet allowed his courtiers and his bishops to
rule over him:
Beginning Of
Reformation.
Et les prêtres en paix guidaient ses faibles ans.
The wife, named Mary, aged eighteen years, was of quite a different
character. A sister of Charles the Fifth, a daughter of the unfortunate
Joanna, queen of Castile and Aragon, who was kept in prison till her
death, partly perhaps because she preferred the Gospel to the pope,
Mary like her mother and still more than her mother had tasted the
doctrine of the Gospel. Of lofty character, with a kindly heart, a
sound understanding, and high intellectual abilities, well informed
and able to speak five languages, it was said of her that she was as
competent to rule over minds in peace as to command armies in
war. She did not actually march at their head, but she once caused a
severe defeat to be given to Henry II., the son of Francis I.
While still very young and residing at the court of her grandfather
Maximilian, she had read with delight the first works of Luther. ‘Her
chamber was her oratory,’ said Erasmus. She loved the chase, but
she did not start for this sport without taking with her her New
Testament. She was equally fond of pursuing on horseback the hart
and the hare, and of sitting under a tree to read the word of the
Saviour. We have elsewhere mentioned the fact that while she was
at Augsburg in 1530, in company with her brother Charles the Fifth
and the archbishops, bishops, and legates of the papacy, she
courageously had the evangelical services celebrated in her
apartments. Melanchthon called her a woman of heroic genius. She
would fain have given her protection to the Reformation in Hungary,
but the influence of the priests over the king was stronger than her
own. Subsequently also she entreated the emperor not to submit to
the domination of the clergy.[522]
It was by a kind of thunder-clap that the
Reformation began in Hungary. In 1518
there appeared a work entitled, De Horrendo Idololatriæ Crimine. In
1520 and 1521 the earliest writings of Luther, on Christian Liberty,
on the Epistle to the Galatians, and others besides, were brought
into the kingdom by traders who came from Germany. The Captivity
of Babylon delighted the Hungarians, and led many of them to
separate themselves from the ultramontane Roman Church. Other
evangelical books explaining the doctrine of salvation were read with
eagerness. Nobles and townsmen declared for the Reformation; and
this they did with all the energy of their national character. The like
events were taking place in Transylvania.
Progress so rapid could not but provoke persecution. It was to begin
with anathemas, but it would soon go on to rigorous deeds, and
would rage almost without intermission.
Szakmary, archbishop of Gran, hoping to annihilate Reform at one
blow, assembled his scribes, and had a public document drawn up.
In 1521 condemnation of Luther and of his writings resounded from
the pulpits of the principal Hungarian churches.[523]
Most of the Hungarians who heard this were very much astonished;
and the publication of the anathemas produced a contrary effect to
that which the prelate had aimed at. It awakened in the hearers a
consciousness of the important nature of the Reformation; so that its
friends were encouraged, and many were led to seek after the truth
who had not previously concerned themselves about it. Many
ecclesiastics, especially, who had been oppressed by the higher
clergy, and had long sighed for the time of justice and freedom, now
lifted up their heads, read the sacred books, and declared that
Luther’s doctrine, founded on the Word of God, alone was true. They
did not remain inactive; but by their living and powerful words they
enlightened the minds of men. Parishes, villages, and towns joyfully
greeted the Reformation.
One of the first to proclaim the Gospel in Hungary appears to have
been Thomas Preussner. Others followed him. Cordatus at Bartfeld,
in 1522, Siklosy at Neustadt, Kopacsy at Sarospatak, Radan and
Husser at Debreczin, and George at Hermanstadt, proclaimed the
tidings of a salvation freely given to those who laid hold on Christ by
faith. Learned men at the same time were bearing witness to the
truth at the university of Buda. Simon Grynaeus, son of a simple
Suabian peasant, and afterwards a friend of Calvin, having from
childhood shown a remarkable disposition for study, had been sent
Hungarians At
Wittenberg.
at the age of fourteen to the famous school of Pforzheim. Thence he
had passed to the university of Vienna, where he distinguished
himself and took the degree of master of arts. The king then called
him to Buda. Grynaeus did not confine himself to teaching letters
there, but openly and boldly announced to the people the great
doctrines of the Gospel which he had embraced with all his heart.
Another doctor, Winsheim, also professed openly the same faith;
and, what was an unlooked-for event, people were talking at Pesth,
in the old capital of the kings, on the banks of the Danube, and near
the borders of Turkey, of that same Word of God which was giving
joy to so many Germans on the banks of the Elbe. The Reformation,
like a broad river, brought life and prosperity into these vast regions
which extend between the Alps, the Carpathian Mountains, and the
Balkan. But, alas! the river, dried up here and there by the parching
heat of persecution, was one day to shrink and be turned into a
stagnant and sleepy body of water like that which runs to lose itself
in the dry sands of the desert.[524]
These times, however, were as yet remote.
The reformation of the Magyars was still in
its period of growth and life. The tidings of the struggle which had
begun in Germany excited in men’s minds a burning desire to see
Luther, to hear him, and to receive from his very lips the heavenly
doctrine.[525]
This is a characteristic feature of the Hungarian
Reformation. The wish to go and drink the living water at its very
source became intense, and all who were able to do so hastened to
Wittenberg. Martin Cyriaci from Leutschau arrived there in 1522. He
was followed in 1524 by Dionysius Link, Balthazar Gleba from Buda,
and a great number of their countrymen.[526]
Joyfully they greeted
the modest city from which light was shed over the world. They
fixed their gaze with timid respect on Luther and on Melanchthon;
took their places on the benches of their auditories; received into
their minds and hearts the words of these illustrious masters, and
engraved them there more indelibly than on the leaves of their note-
books.
Intolerance Of The
Priesthood.
In Hungary it began gradually to be noticed that one student and
another was missing. The cause of their absence became known;
they were gone to Wittenberg. The bishops, provoked at these
heretical pilgrimages, denounced them to the king. These priests
had no difficulty in getting their views adopted by this young man,
who, but a little while before, had given proof of his character. Louis,
who was king of Bohemia as well as of Hungary, had gone to Prague
for the coronation of the queen, Mary; and as he passed through
Moravia he had a parley with the townsmen of Iglau, and had
declared to them that unless they abandoned the Saxon heresy he
would have them put to death. At the same time he had ordered
their pastor, John Speratus, to be thrown into prison. This was the
wedding bouquet which Louis II. presented to his young, lovely, and
Christian spouse, on the occasion of her coronation.[527]
The archbishops and the priests, in
possession of all their privileges, put
themselves at the head of the opposition. Many of them, of course,
were actuated by a higher motive, the glory of the Roman Church;
but in general they had no mind to let what they had usurped be
taken from them. King Louis and other princes, pressed by the
clergy, lent them their own power and authority; but the
ecclesiastics were the authors of the persecution. A religious
philosopher of the eighteenth century[528]
has said, ‘The clergy are
the indirect cause of the crimes of kings. While they talk incessantly
of God, they only aim at establishing their own dominion.’ This is a
strong saying, and the author forgets that in the Catholic Church
there are, and always have been, some good priests and good
laymen. Let us not exaggerate. Still, the empire of the clergy, the
despotism with which it crushed consciences, is a great historical
fact. It concealed the Holy Scriptures, but it brought out its tariffs of
indulgences, its exactions, its punishments with fire and sword. At a
later time the progress of Christian civilization no longer allowed
resort to such barbarous practices. But if evangelical Christianity is
exposed henceforth only to senseless accusations, and frequently to
insults on the part of the adherents of Rome, another adversary has
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com

More Related Content

Similar to ASP NET MVC in Action 1st Edition Jeffrey Palermo (20)

PDF
ASP NET 4 0 in Practice Daniele Bochicchio
sabenaforu
 
PPS
Introduction To Mvc
Volkan Uzun
 
PDF
Learning Aspnet Core Mvc Programming Mugilan T S Ragupathi
nybiadegeye
 
PPT
CTTDNUG ASP.NET MVC
Barry Gervin
 
PDF
ASP NET 4 0 in Practice Daniele Bochicchio
fofangomeal55
 
PPTX
Asp.Net MVC3 - Basics
Saravanan Subburayal
 
PDF
ASP.NET MVC - Whats The Big Deal
Venketash (Pat) Ramadass
 
PDF
ASP.NET MVC 2.0
Buu Nguyen
 
PPTX
MVC 4
Vasilios Kuznos
 
PDF
Aspnetmvc 1
Fajar Baskoro
 
PDF
Asp 1a-aspnetmvc
Fajar Baskoro
 
PPTX
Mvc summary
Muhammad Younis
 
PPT
ASP.NET MVC Presentation
ivpol
 
PPTX
ASPNet MVC series for beginers part 1
Gaurav Arora
 
PPTX
Asp net mvc series for beginers part 1
Gaurav Arora
 
PPTX
ASP.net MVC Introduction Wikilogia (nov 2014)
Hatem Hamad
 
PPTX
ASP.NET MVC Best Practices malisa ncube
Malisa Ncube
 
PDF
Introduction to ASP.NET MVC
Mayank Srivastava
 
PDF
Mastering asp.net mvc - Dot Net Tricks
Gaurav Singh
 
PDF
Architecting ASP.NET Core Applications Carl-Hugo Marcotte
rddhwsf007
 
ASP NET 4 0 in Practice Daniele Bochicchio
sabenaforu
 
Introduction To Mvc
Volkan Uzun
 
Learning Aspnet Core Mvc Programming Mugilan T S Ragupathi
nybiadegeye
 
CTTDNUG ASP.NET MVC
Barry Gervin
 
ASP NET 4 0 in Practice Daniele Bochicchio
fofangomeal55
 
Asp.Net MVC3 - Basics
Saravanan Subburayal
 
ASP.NET MVC - Whats The Big Deal
Venketash (Pat) Ramadass
 
ASP.NET MVC 2.0
Buu Nguyen
 
Aspnetmvc 1
Fajar Baskoro
 
Asp 1a-aspnetmvc
Fajar Baskoro
 
Mvc summary
Muhammad Younis
 
ASP.NET MVC Presentation
ivpol
 
ASPNet MVC series for beginers part 1
Gaurav Arora
 
Asp net mvc series for beginers part 1
Gaurav Arora
 
ASP.net MVC Introduction Wikilogia (nov 2014)
Hatem Hamad
 
ASP.NET MVC Best Practices malisa ncube
Malisa Ncube
 
Introduction to ASP.NET MVC
Mayank Srivastava
 
Mastering asp.net mvc - Dot Net Tricks
Gaurav Singh
 
Architecting ASP.NET Core Applications Carl-Hugo Marcotte
rddhwsf007
 

Recently uploaded (20)

PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Horarios de distribución de agua en julio
pegazohn1978
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Ad

ASP NET MVC in Action 1st Edition Jeffrey Palermo

  • 1. Instant Ebook Access, One Click Away – Begin at ebookgate.com ASP NET MVC in Action 1st Edition Jeffrey Palermo https://ebookgate.com/product/asp-net-mvc-in-action-1st- edition-jeffrey-palermo/ OR CLICK BUTTON DOWLOAD EBOOK Get Instant Ebook Downloads – Browse at https://ebookgate.com Click here to visit ebookgate.com and download ebook now
  • 2. Instant digital products (PDF, ePub, MOBI) available Download now and explore formats that suit you... ASP NET MVC 2 in Action 2nd Edition Jeffrey Palermo https://ebookgate.com/product/asp-net-mvc-2-in-action-2nd-edition- jeffrey-palermo/ ebookgate.com Professional ASP NET MVC 2 1st Edition Jon Galloway https://ebookgate.com/product/professional-asp-net-mvc-2-1st-edition- jon-galloway/ ebookgate.com Test Drive ASP NET MVC 1st Edition Jonathan Mccracken https://ebookgate.com/product/test-drive-asp-net-mvc-1st-edition- jonathan-mccracken/ ebookgate.com Professional ASP NET MVC 1 0 1st Edition Rob Conery https://ebookgate.com/product/professional-asp-net-mvc-1-0-1st- edition-rob-conery/ ebookgate.com
  • 3. What s New in ASP NET MVC 2 1st Edition Simone Chiaretta https://ebookgate.com/product/what-s-new-in-asp-net-mvc-2-1st-edition- simone-chiaretta/ ebookgate.com Pro ASP NET MVC 3 Framework 3rd Edition Steven Sanderson https://ebookgate.com/product/pro-asp-net-mvc-3-framework-3rd-edition- steven-sanderson/ ebookgate.com Bootstrap for ASP NET MVC Second Edition Pieter Van Der Westhuizen https://ebookgate.com/product/bootstrap-for-asp-net-mvc-second- edition-pieter-van-der-westhuizen/ ebookgate.com Expert ASP NET Web API 2 for MVC developers 1st Edition Adam Freeman https://ebookgate.com/product/expert-asp-net-web-api-2-for-mvc- developers-1st-edition-adam-freeman/ ebookgate.com Pro ASP NET Web API HTTP Web Services in ASP NET 1st Edition Tugberk Ugurlu https://ebookgate.com/product/pro-asp-net-web-api-http-web-services- in-asp-net-1st-edition-tugberk-ugurlu/ ebookgate.com
  • 5. M A N N I N G Jeffrey Palermo Ben Scheirman Jimmy Bogard FOREWORD BY PHIL HAACK IN ACTION
  • 6. ASP.NET MVC in Action
  • 8. ASP.NET MVC in Action WITH MVCCONTRIB, NHIBERNATE, AND MORE JEFFREY PALERMO BEN SCHEIRMAN JIMMY BOGARD M A N N I N G Greenwich (74° w. long.)
  • 9. For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. Sound View Court 3B fax: (609) 877-8256 Greenwich, CT 06830 email: [email protected] ©2010 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15% recycled and processed without the use of elemental chlorine. Development Editor: Tom Cirtin Copyeditor: Betsey Henkels Manning Publications Co. Proofreader: Elizabeth Martin Sound View Court 3B Typesetter: Gordan Salinovic Greenwich, CT 06830 Cover designer: Leslie Haimes ISBN 978-1-933988-62-7 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 14 13 12 11 10 09
  • 10. v brief contents 1 ■ Getting started with the ASP.NET MVC Framework 1 2 ■ The model in depth 24 3 ■ The controller in depth 44 4 ■ The view in depth 65 5 ■ Routing 91 6 ■ Customizing and extending the ASP.NET MVC Framework 119 7 ■ Scaling the architecture for complex sites 152 8 ■ Leveraging existing ASP.NET features 174 9 ■ AJAX in ASP.NET MVC 195 10 ■ Hosting and deployment 216 11 ■ Exploring MonoRail and Ruby on Rails 238 12 ■ Best practices 270 13 ■ Recipes 312
  • 12. vii contents foreword xiii preface xv acknowledgments xviii about this book xxi about the authors xxvi about the cover illustration xxviii 1 Getting started with the ASP.NET MVC Framework 1 1.1 Picking apart the default application 3 Creating the project 4 ■ Your first routes 7 ■ Running with the starter project 9 1.2 Your first ASP.NET MVC controller from scratch 14 1.3 Our first view 16 1.4 Ensuring the application is maintainable 18 1.5 Testing controller classes 20 1.6 Summary 22 2 The model in depth 24 2.1 Understanding the basics of domain-driven design 25 2.2 Domain model for this book 26 Key entities and value objects 26 ■ Aggregates 27 ■ Persistence for the domain model 29
  • 13. CONTENTS viii 2.3 Presentation model 31 Presentation model responsibilities 31 ■ Projecting from the domain model 33 2.4 Working with the model 34 Crafting the route 35 ■ Crafting the controller action 35 ■ Test- driving the feature 36 ■ Finishing the view 39 2.5 Summary 42 3 The controller in depth 44 3.1 The controller action 45 3.2 Simple controllers do not need a view 47 3.3 Testing controllers 50 Testing the RedirectController 50 ■ Making dependencies explicit 52 ■ Using test doubles, such as stubs and mocks 53 ■ Elements of a good controller unit test 55 3.4 Simple actions and views 56 3.5 Working with form values 57 3.6 Processing querystring parameters 58 3.7 Binding more complex objects in action parameters 59 3.8 Options for passing ViewData 61 3.9 Filters 62 3.10 Summary 64 4 The view in depth 65 4.1 How ASP.NET MVC views differ from Web Forms 66 4.2 Folder structure and view basics 67 4.3 Overview of view basics 69 Examining the IViewEngine abstraction 70 ■ Understanding master pages in the ASP.NET MVC Framework 71 ■ Using ViewData to send objects to a view 73 ■ Partial views can help decompose a complex screen 76 4.4 Leveraging the view to create dynamic screens 79 Rendering forms with view helpers and data binding 79 ■ Posting HTML forms back to the server 84 ■ Validation and error reporting 85 ■ Extending HtmlHelper 88 4.5 Summary 90
  • 14. CONTENTS ix 5 Routing 91 5.1 What are routes? 92 What’s that curl command? 92 ■ Taking back control of the URL with routing 94 5.2 Designing a URL schema 95 Make simple, clean URLs 95 ■ Make hackable URLs 96 ■ Allow URL parameters to clash 96 ■ Keep URLs short 97 ■ Avoid exposing database IDs wherever possible 97 Consider adding unnecessary information 98 5.3 Implementing routes in ASP.NET MVC 99 URL schema for an online store 102 ■ Adding a custom static route 103 ■ Adding a custom dynamic route 103 ■ Catch-all routes 105 5.4 Using the routing system to generate URLs 107 5.5 Creating routes for Code Camp Server 108 5.6 Testing route behavior 111 5.7 Using routing with existing ASP.NET projects 115 5.8 Summary 117 6 Customizing and extending the ASP.NET MVC Framework 119 6.1 Extending URL routing 120 6.2 Creating your own ControllerFactory 125 The ControllerFactory implementation 126 ■ Leveraging IoC for your controllers 130 6.3 Extending the controller 134 Creating a FormattableController 135 ■ Working with action filters 138 6.4 Creating a custom view engine 141 6.5 Customizing Visual Studio for ASP.NET MVC 145 Creating custom T4 templates 145 ■ Adding a custom test project template to the new project wizard 148 6.6 Summary 150 7 Scaling the architecture for complex sites 152 7.1 Taming large controller actions 153 7.2 Whipping views into shape 156 Using and creating view helpers 156 ■ Creating partials 159 ■ Creating components 163
  • 15. CONTENTS x 7.3 Using action filters to load common data 165 7.4 Organizing controllers into areas 167 Capturing the area for a request 168 ■ Creating a view engine with support for areas 168 ■ Tying it all together 171 7.5 Summary 172 8 Leveraging existing ASP.NET features 174 8.1 ASP.NET server controls 175 The TextBox 175 ■ Other common controls 176 ■ The GridView 178 ■ Where do I get the good stuff? 179 8.2 State management 179 Caching 179 ■ Session state 183 ■ Cookies 184 ■ Request storage 184 8.3 Tracing and debugging 185 TraceContext 186 ■ Health monitoring 186 8.4 Implementing personalization and localization 187 Leveraging ASP.NET personalization 187 ■ Leveraging ASP.NET localization 188 8.5 Implementing ASP.NET site maps 192 8.6 Summary 194 9 AJAX in ASP.NET MVC 195 9.1 Diving into AJAX with an example 196 9.2 AJAX with ASP.NET Web Forms 198 9.3 AJAX in ASP.NET MVC 200 Hijaxing Code Camp Server 201 ■ AJAX with JSON 207 Adding alternate view formats to the controller 208 ■ Consuming a JSON action from the view 210 ■ AJAX helpers 213 9.4 Summary 214 10 Hosting and deployment 216 10.1 Deployment scenarios 217 10.2 XCOPY deployment 218 10.3 Deploying to IIS 7 219 10.4 Deploying to IIS 6 and earlier 223 Configuring routes to use the .aspx extension 224 ■ Configuring routes to use a custom extension 225 ■ Using wildcard mapping with selective disabling 226 ■ Using URL rewriting 229
  • 16. CONTENTS xi 10.5 Automating deployments 232 Employing continuous integration 232 ■ Enabling push-button XCOPY deployments 233 ■ Managing environment configurations 234 10.6 Summary 237 11 Exploring MonoRail and Ruby on Rails 238 11.1 MonoRail 239 Feature overview 239 ■ ActiveRecord and Windsor 248 MonoRail and Castle features available in ASP.NET MVC 255 11.2 Ruby on Rails 255 Convention over configuration and “the Rails way” 256 ■ Active Record 260 ■ ActionPack 264 11.3 Summary 269 12 Best practices 270 12.1 Controllers 271 Layer Supertype 271 ■ Filters 272 ■ Smart binders 274 Hardcoded strings 279 ■ Separated view models 280 Validation 281 12.2 Views 283 Strongly typed views 283 ■ Fighting duplication 284 ■ Embracing expressions 286 12.3 Routes 289 Testing routes 289 ■ Action naming 292 12.4 Testing 294 Controller unit tests 295 ■ Model binder unit tests 298 ■ Action filter unit tests 301 ■ Testing the last mile with UI tests 303 12.5 Summary 311 13 Recipes 312 13.1 jQuery autocomplete text box 312 13.2 Automatic client-side validation 318 13.3 Data access with NHibernate 325 Functional overview of reference implementation 326 Application architecture overview 327 ■ Domain model—the application core 328 ■ NHibernate configuration—infrastructure of the application 330 ■ UI leverages domain model 338 Pulling it together 341 ■ Wrapping up data access with NHibernate 344
  • 17. CONTENTS xii 13.4 Designing views with the Spark view engine 345 Installing and configuring Spark 345 ■ Simple Spark view example 347 13.5 Summary 351 index 353
  • 18. xiii foreword The final version of ASP.NET MVC 1.0 was released March 2009 during the Mix 09 con- ference and nobody was caught by surprise with what was inside—and this is a good thing. Before the debut of the final version, the product team had released multiple public previews with full source code in an effort to raise the bar on openness and community involvement for a Microsoft product. Why would we do this? Transparency and community involvement are noble goals, but they aren’t neces- sarily the end goal of a project. What we’re really after is great product. I like to think of ASP.NET MVC as almost an experiment to demonstrate that transparency and com- munity involvement were great means to achieving that goal. After Preview 2 of ASP.NET MVC was released, we received a lot of feedback from developers that writing unit tests with ASP.NET MVC was difficult. Jeffrey Palermo, the lead author of ASP.NET MVC in Action, was among the most vocal in providing feedback during this time. We took this feedback and implemented a major API change by introducing the concept of action results, which was a much better design than we had before. Community involvement helped us build a better product. ASP.NET MVC focuses on solid principles such as separation of concerns to provide a framework that is extremely extensible and testable. While it’s possible to change the source as you see fit, the framework is intended to be open for extension without need- ing to change the source. Any part of the framework can be swapped with something else of your choosing. Don’t like the view engine? Try Spark view engine. Don’t like the way we instantiate controllers? Hook in your own dependency injection container.
  • 19. FOREWORD xiv ASP.NET MVC also includes great tooling such as the Add View dialog, which uses code generation to quickly create a view based on a model object. The best part is that all the code generation features in ASP.NET MVC rely on T4 templates and are thus completely customizable. With this book, Jeffrey will share all these features and more, as well as show how to put them together to build a great application. I hope you enjoy the book and share in his passion for building web applications. Keep in mind that this book is not only an invitation to learn about ASP.NET MVC, but also an invitation to join in the commu- nity and influence the future of ASP.NET MVC. Happy coding! PHIL HAACK SENIOR PROGRAM MANAGER ASP.NET MVC TEAM MICROSOFT
  • 20. xv preface My career started in the mid-nineties as one of the early web developers. Web as in HTTP, that is. Netscape Navigator was helping to grow the number of households with internet modems because it was more advanced than anything else at the time. Netscape Navigator 3.0 (1996) and 3.04 (1997) helped households and businesses all over the world open up the internet for common uses. There is no more common a task than shopping! With the advent of ecommerce, the internet exploded with a cap- italist gold run. I started web development in the public sector where we leveraged the first threads of social networking by allowing school district graduates to collaborate with former classmates. I started my career on the Microsoft platform using IDC (Internet Database Connector) with HTX (HTML Extension Template). Internet Information Services (IIS) 2.0 gave us fantastic flexibility using ODBC data sources. This was my first use of the “code nugget,” or <% %> delimiters. IDC/HTX gave way to Active Server Pages (ASP), and I can still recall following the changes as they broke–ASP 2.0 to ASP 3.0 as well as the awe- some COM+ integration. I dabbled in CGI, Perl, Java, and C++, but stayed with the Microsoft platform. Observing the Visual Basic explosion from the sidelines, I learned the ropes with small utility apps. Active Server Pages 3.0 saw the browser wars with Internet Explorer 4, released with Windows 95, competing with Netscape for market share. Writing web applica- tions that worked well with both browsers was difficult. IE 5.0 opened the horizons for intranet applications with proprietary web extensions like the XML data island and better scripting capabilities. Windows XP shipped with IE 6, which effortlessly cap- tured the majority of the web browser market. ASP 3.0 put the programmer intimately
  • 21. PREFACE xvi in touch with HTTP, HTML, and the GET and POST verbs. I remember pulling out crude frameworks to handle multiple request paths from the same ASP script. At the same time ASP 3.0 was enjoying widespread adoption, Struts was taking the Java web application world by storm. Struts is probably the best known Java MVC frame- work, although today there are many popular frameworks for the JVM. With ASP 3.0, I was unaware of the lessons my Java counterparts had already learned, although I felt the pain of myriad responsibilities lumped into a single ASP script. I adopted ASP.NET 1.0 right out of the gate and converted some of my ASP 3.0 sites to Web Forms. Remember when GridLayout was the default with CSS absolute posi- tioning everywhere? It was clear that Web Forms 1.0 was geared for VB6 developers coming over to .NET and getting onto the web. The post-backs and button click han- dlers were largely foreign to me, but my colleagues who were seasoned VB6ers felt right at home. ASP.NET 1.1 dropped the GridLayout and forced the developer to understand HTML and how flow layout works. Down-level rendering was great when Internet Explorer was the “preferred” browser, and everything else was downlevel. That paradigm started to break down as Firefox climbed in market share and demanded standards-compliant markup. I became an ASP.NET expert and was a frequent blogger during the .NET 2.0 beta cycle. I knew every feature and every breaking change from ASP.NET 1.1 to 2.0, and helped my team adopt 2.0. During the ASP.NET 2.0 era, I started following Martin Fowler and his Model-View-Presenter writings. I implemented that pattern to pull away logic from the code-behind file, which had become bloated. Java developers, in 2005, were enjoying a choice of several MVC frameworks for the web. I, on the other hand, was wrestling Web Forms into Model-View-Presenter and test-driven development submis- sion. It was exhausting, but what was the alternative? In 2006, with a job change, I jumped over to software management and smart client development with WinForms. With the familiar clunkiness of the code-behind model, and a development team to manage, I implemented the Model-View-Controller pattern with the WinForm class as the view. It was a breath of fresh air. UI development was seamless, and the controllers were a natural boundary from the domain model to the UI. In 2007, I jumped back into web development and begrudgingly implemented Model-View-Presenter with Web Forms again. In retrospect, I wish I had adopted Mono- Rail, another Model-View-Controller framework for .NET. In February 2007, Scott Guthrie (ScottGu) created a prototype of what would become the ASP.NET MVC framework. He had heard from many customers about the difficulties with Web Forms and how they needed a simpler, more flexible way to write web applications. At the 2007 MVP Summit, Scott sought input from a small group of Microsoft MVPs. Darrell Norton, Scott Bellware, Jeremy Miller, and I validated the vision of his prototype and gave initial input that would end up coded into the framework. When Scott Guthrie presented, to an audience in Austin, Texas, a working proto- type and vision for ASP.NET MVC at the AltNetConf open spaces conference in Octo- ber 2007, I knew instantly that this is what I’d wished for all along. As a long-time web developer, I understood HTTP and HTML, and this, I believe, is what ASP.NET 1.0 should have been. It would have been such a smooth transition from ASP 3.0 to
  • 22. PREFACE xvii ASP.NET MVC. I can claim the first ASP.NET MVC application in production because I convinced Scott to give me a copy of his prototype and revised my www.partywithpal- ermo.com registration site, launching it in November 2007 on one of Rod Paddock’s servers at DashPoint. What Microsoft did with the ASP.NET MVC release cycle was an unprecedented project in the Developer Division. The project was released at least quarterly on the CodePlex site, source code and all. It was also developed using test-driven develop- ment as the software construction technique. Full unit test coverage is included in the source code download, and ASP.NET MVC 1.0 was released under the MS-PL, and OSI- approved open source license. ASP.NET MVC works the way the web works; it’s a natural fit. Although Microsoft is last to the table with a Model-View-Controller framework for its development plat- form, this framework is a strong player. Its design focuses on the core abstractions first. It is conducive to extension by the community. In fact, the same week the first Community Technology Preview (CTP) was released, Eric Hexter and I launched the MvcContrib open-source project with an initial offering of extensions that integrated with the ASP.NET MVC Framework. At the time of publishing this book, the ASP.NET MVC framework is a frequently used tool at Headspring Systems, where I facilitate the consulting practice. For the .NET industry as a whole, I predict that ASP.NET MVC will be considered the norm for ASP.NET development by 2011. New developers are coming to the .NET platform every day, and for web develop- ers, ASP.NET MVC is easy to adopt and learn. Because of the decreased complexity, the barrier to adoption is lowered, and because of the simplicity, it can grow to meet the demands of some of the most complex enterprise systems. When Manning Publications approached me to write a book on ASP.NET MVC, I was already a frequent blogger on the topic and had published an article on the framework in CoDe magazine. Even so, I knew writing a book would be a tremendous challenge. This book has been in progress for over a year, and I am excited to see it published. I learned quite a bit from Ben and Jimmy throughout this project, and I learned so much more about the framework by writing about it. This knowledge has direct and immediate benefit to our client projects. Our hope is that our book will stay with you even after you have written your first application. Writing a book published just after a 1.0 release is challenging because many things are discovered after a technology has been out in the wild. Leveraging it on client projects immediately has definitely helped increase the quality of informa- tion contained in the book because it is derived from hands-on experience. Although other platforms have benefited from Model-View-Controller frameworks for many years, the MVC pattern is still foreign to many .NET developers. This book explains how and when to use the framework; also the theory and principles behind the pattern as well as complimentary patterns. We hope that this book will enlighten your understanding of an indispensable technology that’s simple to learn. JEFFREY PALERMO
  • 23. xviii acknowledgments We’d like to thank Scott Guthrie for seeing the need in the .NET space for this frame- work. Without his prototype, vision, and leadership, this offering would still not exist in the .NET framework. We would also like to recognize the core ASP.NET MVC team at Microsoft, headed by Phil Haack, the Program Manager for ASP.NET MVC. Other key members of the ASP.NET MVC team are Eilon Lipton (Lead Dev), Levi Broderick (Dev), Jacques Eloff (Dev), Carl Dacosta (QA), and Federico Silva Armas (Lead QA). We would also like to extend our thanks to the large number of additional staff who worked on packaging, documenting and delivering the ASP.NET MVC framework as a supported offering from Microsoft. Even though this framework is small compared to others, this move from Microsoft is shifting the mental inertia of the .NET portion of the software industry. This book employed three working authors, all consultants with multiple projects, along with startup help and a chapter draft by Dave Verwer. The book efforttook over a year and a half, starting with the first Community Technology Preview of the ASP.NET MVC Framework. This dynamic required tremendous support from the staff at Manning Publications. We would like to thank them for their patience and support throughout the project. In particular, we would like to thank acquisitions editor Michael Stephens and editor Tom Cirtin for their leadership. Michael saw the need for this book and contacted me about writing it. Tom was very supportive and patient and helped the three of us through our first book publication. Our independent technical reviewers were outstanding. They offered advice and opinionated viewpoints on each chapter during development, and without that input,
  • 24. ACKNOWLEDGMENTS xix the book would not be as good as we hope it is. Our sincere thanks goes to Phil Haack for reviewing the manuscript and writing a brilliant foreword. Many thanks should also go to Freedom Dumlao, who painstakingly reviewed each chapter to ensure the message would apply in the best manner to the target audience. Jeremy Skinner was also a boon to the project. Jeremy tested and retested every code listing and code sam- ple in the book as well as in the many Visual Studio projects that come with the book. His attention to detail, backed up by his vast experience with ASP.NET MVC and Mvc- Contrib, has contributed greatly to this book. Manning invited the following reviewers to read the manuscript at different stages of development and to send their comments: Mark Monster, Andrew Siemer, Benja- min Day, Frank Wang, Derek Jackson, Tim Binkley-Jones, Marc Gravell, Alessandro Gallo, Josh Heyer, Peter Johnson, Jeremy Anderson, and Alex Thissen. This book has also benefited from outside technical reviewers who volunteered to read parts of the manuscript and provided feedback: Rod Paddock, Craig Shoemaker, Hamilton Verissimo, Matt Hinze, Kevin Hurwitz, Blake Caraway, Nick Becker, Mahen- dra Mavani, Eric Anderson, Rafael Torres, Eric Hexter, Tom Jaeschke, Matt Hawley, and Sebastien Lambla. Before this book went to print, a large number of people purchased the PDF edi- tion of the book by participating in the MEAP, Manning’s Early Access Program. We would like to thank those readers for their comments and participation early, and throughout the manuscript portion of the project, especially Eric Kinateder, Ben Mills, Peter Kellner, Jeff P., Orlando Agostinho, Liam McLennan, Ronald Wildenberg, Max Fraser, Gudmundur.Hreidarsson, Kyle Szklenski, Philippe Vialatte, Lars Zeb, Marc Gravell, Cody Skidmore, Mark Fowler, Joey Beninghove, Shadi Mari, Simone Chiaretta, Jay Smith, Jeff Kwak, and Mohammad Azam. JEFFREY PALERMO I would like to thank my beautiful wife, Liana, for her support and patience through- out this project. Liana gave birth to our daughter, Gwyneth Rose, shortly before the book was started, and the motivation to spend more time with my growing family pushed me to complete the book. Thanks also to my parents, Peter and Rosemary Pal- ermo, for instilling in me a love of books and learning from an early age. BEN SCHEIRMAN My thanks and utmost appreciation go out to my amazing wife, Silvia. Her continued support and encouragement of my extracurricular work led to writing this book in the first place. I would also like to recognize one of my university mentors, Venkat Subra- maniam. With his guidance, I found my passion in software development and strived to learn more and push the envelope. He was an inspiration in my career. Finally I’d like to thank my wonderful children, Andréa, Noah, and Ethan (and most recently Isaac and Isabella), who showed immense patience and encouragement while their dad was banging away at the keyboard in the late hours of the night.
  • 25. ACKNOWLEDGMENTS xx JIMMY BOGARD Thanks to my wife, Sara, without whose love, support, and patience, my contribution to this project would not have been possible. Also, thanks to my family for putting up with a strange little bookworm all those years. Finally, thanks to my high school com- puter science teacher, Scotty Johnson, who showed me the rewards that a true passion for the craft can bring.
  • 26. xxi about this book The ASP.NET MVC Framework was a vision of Scott Guthrie in early 2007. With a proto- type demonstration in late 2007 as well as a key hire of Phil Haack as the Senior Pro- gram Manager of the feature team, Scott made the vision a reality. At a time when the .NET community was becoming frustrated that other platforms had great MVC frame- works like Tapestry, Rails, and so on, Web Forms was losing favor as developers strug- gled to make it do things previously unimagined when it became public in 2001. Castle MonoRail was a very capable framework and continues to have strong leadership behind it, but the broader .NET industry needed a change from Web Forms. Phil Haack, with his experience outside of Microsoft as well as in the open source commu- nity, immediately came in and led the ASP.NET MVC Framework team to a successful 1.0 release that the .NET community is excited about. ASP.NET MVC has the benefit of lessons learned from other popular MVC frame- works such as Struts, WebWork, Tapestry, Rails, and MonoRail. It also came about as C# starts to push away its fully statically typed roots. The language enhancements introduced with .NET 3.5 have been fully leveraged in the ASP.NET MVC Framework, giving it a huge advantage over frameworks that came before as well as all the Java frameworks that are tied to the currently supported Java syntax. For people who have a diversified software background, ASP.NET MVC is a great addition to the Visual Studio development experience. For those who began their software career with .NET 1.0 or later, it is a fundamental shift in thinking since they grew up with Web Forms being “normal” web development. This book attempts to start at a point that is past the documentation and online tutorials available on the ASP.NET MVC website at http://www.asp.net/mvc/. If you are
  • 27. ABOUT THIS BOOK xxii just getting started with ASP.NET, you will want to read some of the older books cover- ing the ASP.NET pipeline and server runtime. Because ASP.NET MVC layers on to ASP.NET, it is important to understand the fundamentals. If you are a current ASP.NET developer, you will find that this book does not insult your intelligence. It is a fast- paced book aimed at giving you the why and not just the how. Since ASP.NET MVC is a new technology offering you can expect several books to cover the topic. This is a framework that is not sitting still. Since its release in March 2009, several books have been released, but the community is finding new and better ways to use the framework. The newest ideas make their way to the Mvc- Contrib project, and to public release frequently as new additions are contributed. Because of this dynamic, this book covers ASP.NET MVC with MvcContrib sprinkled throughout. The authors are all actively developing with the framework, and MvcCo- ntrib plays a vital part in every application. This books aims to have a long-lasting place on your bookshelf. The API will evolve, but the principles behind using an MVC framework as well as the ways to structure URLs, tests, and application layers are more durable. With this, we hope that this book serves not only as a rigorous foray into ASP.NET MVC development but also as a guide toward developing long-lived web applications on the .NET platform. We hope that the arrival of this book is considered good timing because the text was written with the perspective of the roadmap of ASP.NET MVC 2.0 in mind. With the roadmap plans released and the first CTP of v2 already available, the techniques in this book are useful now and are also relevant for ASP.NET MVC v2, which is quickly approaching. We hope this book will help you start on your way to creating many maintainable, long-lived applications on the new version of ASP.NET. Who should read this book? This book is written for senior developers working with ASP.NET. The authors are senior and strong leaders in their companies, local community, and the industry. All three authors are recognized by Microsoft with the Microsoft Most Valuable Profes- sional (MVP) award. With that in mind, we felt it appropriate to write a book aimed at senior members of the software team. With the market flooded with beginner books and books that reformat online documentation and tutorials, we attempted to write a book that might leave some beginners behind but at the same time challenge senior developers and architects. Whether or not you are familiar with other MVC frame- works, this book will push your knowledge further than you are accustomed to when reading a technology book. The book comes with a full reference implementation in production at http:// CodeCampServer.com. CodeCampServer was developed by the authors and is open source with many other contributors at this time. CodeCampServer is an ASP.NET MVC application aimed at hosting user group websites and websites for .NET user group conferences, frequently called Code Camps. The codebase was developed using Onion Architecture, domain-driven design, test-driven development, and inversion of con- trol. The techniques espoused in the book are implemented in the project. Many of
  • 28. ABOUT THIS BOOK xxiii the code examples in the book are detailed explorations of parts of CodeCampServer. Although the project will continue to evolve after this book is published, the princi- ples with which it and the text were written are timeless and portable beyond a single version of the technology. Because in any real project, like CodeCampServer, you use many libraries for specific things, we did not shy away from using these as well. We feel that avoiding other libraries for the sake of simplicity also makes it difficult for the reader to apply the knowledge gained while reading. With that in mind, we use popular libraries such as MvcContrib, NAnt, NUnit, StructureMap, Windsor, Castle, RhinoMocks, Log4Net, NHibernate, Tarantino, AutoMapper, Iesi.Collections and many others. Because real projects have a collage of libraries, we felt that learning ASP.NET MVC in this realistic setting was most appropriate. We have taken care to separate concerns when necessary. We always sepa- rate data access from the domain model and the presentation layer, and we separate pre- sentation model from views; you will not see simplistic examples such as performing a query directly from a UI controller. This is bad practice in anything but the most trivial applications such as that serving http://PartyWithPalermo.com (a three-page site). Real applications have many screens, the embedding data access and other logic in the UI is a recipe for a codebase that is very costly to maintain. We’ve done our best to call out where we expect existing ASP.NET knowledge to tie the example together, but if you find yourself wondering what an HTTP module is, you will probably want to read one of the earlier ASP.NET books. Roadmap Chapter 1 throws the reader directly into code by picking apart the default project template. After a primer on routes, the text moves through a simple controller and view and moves to initial maintainability. The chapter follows up by covering the basics of testing controllers. Chapter 2 moves into the model. It covers not only the domain model of the appli- cation but also the need for different types of models depending on usage, such as a presentation model. Because the authors consider using a presentation model, com- monly called view model, essential for the maintainability for nontrivial systems, it is used right away. Chapter 3 covers controller details. The controller can be very simple or quite complex, and the text covers both. The chapter explores working with form values and querystring values, and it covers model binding, which is one of the most-needed abstractions for ASP.NET to date. Chapter 3 concludes after outlining all the available extension points that are built in. Chapter 4 gives further insight into views. After outlining the key abstractions in the default view engine, it pulls the reader along to essential concepts such as layouts, partial views, and building your own validation and HTML helpers. Chapter 5 goes deeper than you will ever need into routing. Although most proj- ects will not need this amount of advanced routing, we explore the topic thoroughly. We cover the why and not just the how of crafting URLs. From designing a URL schema
  • 29. ABOUT THIS BOOK xxiv to adding dynamic routes, this chapter is a comprehensive guide to the most flexible routes you will need. Chapter 6 explores the many ways to customize and extend the ASP.NET MVC Framework. It starts with custom route handlers and moves to when, why, and how to create your own controller factory. Two Inversion of Control containers are covered in the controller factory section: Windsor and StructureMap. Because most nontrivial applications will want to use a custom controller factory, this section is covered thor- oughly. Next the chapter moves through the ways to extend the controller with action invokers and filters. After a custom view engine and using the new T4 templates, the reader will have the full picture of the available extension points. Chapter 7 communicates ways to scale the architecture for more complex sites. The first is solving the problem of large controller actions and how to move multiple, ill-placed responsibilities out of the controller. View helpers are also covered in more detail as well as techniques for segmenting large views into a number of cohesive smaller ones. The chapter also covers larger issues encountered with action filters. Chapter 8 offers ways to leverage existing ASP.NET features in an ASP.NET MVC appli- cation. The text covers how to use existing server controls, then moves to caching, both output caching and using request level caching provided by HttpContext.Items. It then moves through tracing, health monitoring, site maps, personalization, localization, linq, cookies, session state, and configuration. Because ASP.NET MVC is an add-on to ASP.NET and not a replacement, this chapter ensures the reader understands where all these existing features fit. Chapter 9 has been one of the most popular chapters in the early access program because now, in mid-2009, AJAX is a hot topic. We first lay down our opinionated view on AJAX and then outline the most common uses and techniques for it starting with simple HTML replacement. The chapter covers implementing a REST API with con- trollers as well as some of the third-party libraries and controls available for AJAX. The chapter also outlines ways to make controller actions automatically support AJAX. Chapter 10 covers hosting and deployment. Though not as sexy of a topic as AJAX, it is critical to understand how to deploy applications built on this framework to IIS5/6/7/7.5. All versions are covered in detail as well as the implications of using extensions, wildcard mappings, and URL rewriting. After covering XCopy deploy- ment, the chapter delivers techniques for managing production and development environment settings. The chapter closes out with an autodeployment example that is similar to how CodeCampServer is autodeployed in the wild. Chapter 11 explores MonoRail and Ruby on Rails as a comparison and benchmark against ASP.NET MVC. It starts out with MonoRail and covers validation, data access with ActiveRecord, as well as the view engine choices. Rails follows closely on its heels with “The Rails Way,” ActiveRecord and ActionPack. The purpose of the chapter is to give the reader some familiarity with competing MVC frameworks because good ideas come from everywhere.
  • 30. ABOUT THIS BOOK xxv Chapter 12 uses the controversial title, “Best Practices.” We outline the context that these practices support. We outline best practices for controllers, views, routes, and testing. Each topic has very opinionated recommendations borne from real-world usage of ASP.NET MVC in this type of application. Chapter 13 provides four comprehensive recipes that can be easily implemented on your project. One of the larger chapters, it starts with using jQuery for an autocom- plete text box and then moves on to how to implement automatic client-side data vali- dation. Data access with NHibernate is the next recipe and provides a full vertical slice implementation for calling data access backed by NHibernate from controllers. It out- lines how to map and configure NHibernate as well as some basic mapping and query- ing techniques. The chapter wraps up with a full Spark view engine implementation for those who don’t like the tag format of Web Forms. Code conventions and downloads All source code in listings or in text is in a fixed-width font like this to separate it from ordinary text. Code annotations accompany many of the listings, highlighting important concepts. In some cases, numbered bullets link to explanations that follow the listing. The source code for the examples in this book is available online from the pub- lisher’s website at http://www.manning.com/ASP.NETMVCinAction. Author Online The purchase of ASP.NET MVC in Action includes free access to a private web forum run by Manning Publications, where you can make comments about the book, ask techni- cal questions, and receive help from the author and from other users. To access the forum and subscribe to it, point your web browser to http://www.manning.com/ ASP.NETMVCinAction. This page provides information about how to get on the forum once you’re regis- tered, what kind of help is available, and the rules of conduct on the forum. Man- ning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the authors can take place. It’s not a commitment to any specific amount of participation on the part of the authors, whose contribution to the book’s forum remains voluntary (and unpaid). We suggest you try asking them some challenging questions, lest their interest stray! The Author Online forum and the archives of previous discussions will be accessi- ble from the publisher’s website as long as the book is in print.
  • 31. xxvi about the authors JEFFREY PALERMO is the CTO of Headspring Systems. Jeffrey spe- cializes in Agile management coaching and helps companies double the productivity of software teams. He is instrumental in the Austin software community as a member of AgileAustin and a director of the Austin .NET User Group. Jeffrey has been recognized by Microsoft as a “Microsoft Most Valuable Profes- sional” (MVP) in Solutions Architecture for five years and par- ticipates in the ASPInsiders group, which advises the ASP. NET team on future releases. He is also certified as a MCSD.NET and ScrumMaster. Jeffrey has spoken and facilitated at industry conferences such as VSLive, DevTeach, the Micro- soft MVP Summit, various ALT.NET conferences, and Microsoft Tech Ed. He also speaks to user groups around the country as part of the INETA Speakers’ Bureau. His web sites areheadspringsystems.comandjeffreypalermo.com.HeisagraduateofTexasA&M Uni- versity, an Eagle Scout, and an Iraq war veteran. Jeffrey is the founder of the Code- CampServer open-source project and a cofounder of the MvcContrib project. Jeffrey Palermo is responsible for the popular Party with Palermo events that precede major Microsoft-focused conferences. Started in June of 2005, Party with Palermo has grown in popularity and size. Typical events host hundreds of people for free drinks and food and door prizes. It is the perfect way to hook up with friends and colleagues before the conference week begins. You can see past and upcoming parties at http://party- withpalermo.com where the website has run on ASP.NET MVC since October 2007.
  • 32. ABOUT THE AUTHORS xxvii BEN SCHEIRMAN is a software developer specializing in .NET. He has worked extensively on the web on various platforms and languages. Ben is a Microsoft MVP, Microsoft ASP Insider, and Certified ScrumMaster. When not programming, Ben enjoys speaking, blogging, spending time with his wife and five wonderful children, or voiding warranties on his latest gadgets. Ben is a Principal Consultant with Sogeti in Hous- ton, Texas. Read his blog online at http://flux88.com. JIMMY BOGARD is a Principal Consultant at Headspring Systems. He is an agile software developer with six years of professional development experience. He has delivered solutions from conception to production for many clients. The solutions delivered by Jimmy range from shrink-wrapped products to enterprise ecommerce applications for Fortune 100 custom- ers. He is also a Microsoft Certified Application Developer (MCAD) and is an active member in the .NET community, lead- ing open-source projects, giving technical presentations and facilitating technical book clubs. Currently, Jimmy is the lead developer on the NBehave project, a Behavior-Driven Development framework for .NET, AutoMapper, a convention-based object-to-object mapper and the facilitator of the Austin Domain-Driven Design Book Club. Jimmy is a member of the ASPInsiders group, and received the “Microsoft Most Valuable Profes- sional” (MVP) award for ASP.NET in 2009. About the technical reviewers JEREMY SKINNER lives in the UK and works as a software devel- oper. Most of his work involves writing web applications using ASP.NET and C#. He is involved with several open-source proj- ects including MvcContrib, Fluent Validation, and Fluent Linq to Sql. Jeremy has been invaluable to this book project by reviewing each paragraph of text, each figure, and code example. He found and corrected numerous errors, and this book would not be a good book without him. He is capable of being an author himself, and we fully expect full books out of him in the future. Jeremy’s experience with the ASP.NET MVC framework as well as popular third-party frameworks such as Castle has made him a strong reviewer. His blog can be found at http://www.jeremyskinner.co.uk/. FREEDOM DUMLAO is a software engineer working primarily in .NET. He has a blog at http://weblogs.asp.net/FreedomDumlao/. Freedom reviewed the first drafts of each chapter and made critical suggestions for improvement. His perspective was very valu- able to the quality of the book.
  • 33. xxviii about the cover illustration The figure on the cover of ASP.NET MVC in Action is captioned “L’Habitant de Ver- sailles” which means a resident of the town of Versailles. Today, Versailles is a suburb of Paris with a population of over 90,000, but in the past it was famous both as the cap- ital city of France for a number of years in the 17th and 18th centuries and for the Pal- ace of Versailles around which the city grew. The illustration is taken from a 19th century edition of Sylvain Maréchal’s four- volume compendium of regional dress customs published in France. Each illustration is finely drawn and colored by hand. The rich variety of Maréchal’s collection reminds us vividly of how culturally apart the world’s towns and regions were just 200 years ago. Isolated from each other, people spoke different dialects and languages. In the streets or in the countryside, it was easy to identify where they lived and what their trade or station in life was just by what they were wearing. Dress codes have changed since then and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different conti- nents, let alone different towns or regions. Perhaps we have traded cultural diversity for a more varied personal life—certainly for a more varied and fast-paced technolog- ical life. At a time when it is hard to tell one computer book from another, Manning cele- brates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Maréchal’s pictures.
  • 34. 1 Getting started with the ASP.NET MVC Framework Depending on how long you’ve been building web applications on the Microsoft platform, you’ll relate to some or all of the following pain. In the 1990s, developers built interactive websites using executable programs that ran on a server. These pro- grams (Common Gateway Interface [CGI] was a common technology at the time) accepted a web request and were responsible for creating an HTML response. Tem- plating was ad hoc, and the programs were difficult to write, debug, and test. In the late 1990s, Microsoft, after a brief stint with HTX templates and IDC connectors, introduced Active Server Pages, or ASP. ASP brought templating to web applications. This chapter covers ■ Running the starter project ■ Progressing through Hello World examples ■ Routing basics ■ Unit testing basics
  • 35. 2 CHAPTER 1 Getting started with the ASP.NET MVC Framework The server page was an HTML document with dynamic script mixed in. Although this was a big step forward from the alternatives, the world soon saw massive server pages with code indecipherable from the markup. In early 2002, along came ASP.NET and the Web Forms Framework. Web Forms were a complete shift for ASP developers, partly because they moved most program logic into a class file (called a code-behind) and replaced the HTML markup with dynamic server controls written in an XML syntax. Although performance increased, and the debugging experience improved, new problems arose. The new server-side postback event lifecycle caused newsgroups to explode with activity as confused developers searched for that magic event in which to add those two simple lines of code necessary to make the page work as needed. ViewState, although good in theory, broke down as the application scaled with complexity. Simple pages surpassed 100KB in size, as the entire state of the application had to be stored in the output of every generated page. Development best practices were ignored as tools like Visual Studio encouraged data access concerns like SQL queries to be embedded within view logic. Perhaps the greatest sin of the Web Forms Framework was the tight coupling to everything in the System.Web namespace. There was no hope of unit test- ing any code in the code-behind file, and today we see Page_Load methods that take several trees to print. Although early versions of Web Forms had some drawbacks, ASP.NET and the larger .NET Framework have made huge inroads into the web appli- cation market. Today we see major websites such as CallawayGolf.com, Dell.com, News- week.com, WhiteHouse.gov, and Match.com all running on ASP.NET. The platform has proven itself in the marketplace, and when combined with IIS running on Windows, ASP.NET can easily support complex web applications running in large data centers. The ASP.NET MVC Framework leverages the success of ASP.NET and Web Forms to pro- pel ASP.NET forward as a leader in the web application development space. The ASP.NET MVC Framework has been introduced to simplify the complex parts of Web Forms application development while retaining the power and flexibility of the ASP.NET pipeline. The ASP.NET infrastructure and request pipeline, introduced in .NET 1.0, stay the same, and ASP.NET MVC provides support for developing ASP.NET applications using the Model-View-Controller web presentation pattern. The concerns of the data model, the application logic, and data presentation are cleanly separated, with the application logic kept in a class separated from hard dependencies on how the data will be presented. Server pages have become simple views, which are nothing more than HTML templates waiting to be populated with objects (models) passed in by the controller. The postback event lifecycle is no more, and ViewState is no longer necessary. In this chapter, we’ll walk through your first lines of code built on top of the ASP.NET MVC Framework. After this primer, you’ll be ready for more advanced topics. In this chapter, and throughout the book, we assume that the reader has knowl- edge of ASP.NET. If you’re new to ASP.NET, please familiarize yourself with the ASP.NET request pipeline as well as the .NET runtime. Throughout this chapter, we’ll take you through creating an ASP.NET MVC Framework web application project, creating your
  • 36. 3 Picking apart the default application first routes, controllers, and views. We’ll comb through the default application and explain each part. Then we’ll extend it, and you’ll create your first controller and view. First, let’s explore the MVC pattern and the default application template pro- vided with the framework. 1.1 Picking apart the default application In this section, we’ll explain what the MVC pattern is and create our first ASP.NET MVC Web Application. We’ll focus first on the controller because in the Model-View- Controller triad, the controller is in charge and decides what model objects to use and what views to render. The controller is in charge of coordination and executes first when the web request comes in to the application. The controller is responsible for deciding what response is appropriate for the request. The Model-View-Controller pattern is not new. A core tenet of the MVC pattern is to separate control logic from the view, or a screen. A view is only responsible for ren- dering the user interface. By separating domain logic and decoupling data access and other calls from the view, the UI can stay the same even while logic and data access changes within the application. Figure 1.1 shows a simple diagram of the MVC triad. Note that the controller has a direct relationship with the view and the model, but the model does not need to know about the controller or the view. The web request will be handled by the controller, and the controller will decide which model objects to use and which view objects to render. Integrating with or migrating from ASP.NET Web Forms applications Can we create screens that leverage the ASP.NET MVC Framework while others con- tinue to work using Web Forms? Of course we can. They can run side by side until the entire application is MVC. Using the MVC framework is not an all-or-nothing proposi- tion. There are many, many ASP.NET applications in production using Web Forms. If a software team wants to migrate the application from Web Forms to ASP.NET MVC, it’s possible to do a phased migration and run the two side by side in the same App- Domain. ASP.NET MVC does not replace core ASP.NET libraries or functionality. Rath- er, it builds on top of existing ASP.NET capabilities. The UrlRoutingModule that we registered in the web.config file causes an incoming URL to be evaluated against the existing routes. If a matching route is not found, ASP.NET will continue on and use Web Forms to fill the request, so it’s pretty simple to mix and match features during a migration or for the purpose of application extension. Although Web Forms is not going away any time soon, we believe that controllers, ac- tions, and views will be the preferred way to write ASP.NET applications going into the future. Although Microsoft will continue to support both options (and active develop- ment on the next version of Web Forms continues), we believe that the ASP.NET MVC Framework will be favored over Web Forms much like we see C# favored over VB in documentation, industry conferences, and technical books.
  • 37. 4 CHAPTER 1 Getting started with the ASP.NET MVC Framework To begin, we’ll open up Visual Studio 2008 SP1 and create our project. The edition of Visual Studio 2008 makes a difference. Although there are some workarounds to using the ASP.NET MVC Framework without SP1, System.Web.Abstractions.dll and System.Web.Routing.dll are in the GAC (global assembly cache) as of SP1. You can use Visual Studio 2008 Professional, a Team Edition SKU, or Visual Web Developer Express SP1. Note that the ASP.NET MVC Framework builds on top of Web Application Projects, and although it’s possible to make it work with websites, the development experience is optimized for use with Web Application Projects. NOTE You must already have Visual Studio 2008 SP1 or Visual Web Develop- er 2008 SP1, .NET 3.5 SP1, and the ASP.NET MVC Framework installed to proceed. The MVC framework is an independent release that builds upon .NET 3.5 Service Pack 1. The examples in this book will use Visual Studio 2008 SP1, but you can find information on using the free Visual Web Developer Express 2008 SP1 on the ASP.NET MVC website: http:// www.asp.net/mvc/. We’ll begin in Visual Studio 2008 Professional SP1 by creating a new ASP.NET MVC Web Application project. When you pull up the New Project dialog, make sure you have .NET Framework 3.5 selected. If you have .NET Framework 3.0 or 2.0 selected, Visual Studio will filter the list, and you’ll not see the project template for ASP.NET MVC Web Application. Now that you understand the basics of the pattern and how to install the MVC framework, we’ll dive into our first project. 1.1.1 Creating the project Creating your first ASP.NET MVC Web Application project will be one of the simplest things you do in this chapter. In Visual Studio 2008, when you have .NET Framework 3.5 selected as the target framework, you’ll see a new project template named ASP.NET MVC Web Application. Choose this project template. The new project dialog will look like that shown in figure 1.2. We’re going to be working with a C# ASP.NET MVC Web Application project. You have two options for creating the project. When you click OK, the IDE will ask you about creating a test project. Decide if you’d like it done for you or if you’d rather create the unit test project yourself. For this example, we’ll choose the ASP.NET MVC Web Appli- cation with the test project. Figure 1.3 shows the solution structure of the default Visual Studio template. Since this is not a beginners’ book, we’ll skip the hand-holding and go straight into the project. Model Controller View Figure 1.1 A simple diagram depicting the relationship between the Model, View, and Controller. The solid lines indicate a direct association, and the dashed lines indicate an indirect association (graphic and description used with permission from Wikipedia).
  • 38. 5 Picking apart the default application NOTE More ASP.NET MVC starter kits and sample applications are available from the community on the ASP.NET website. At the time of writing, http:// www.asp.net/community/projects/ and http://www.asp.net/mvc/ have several starter kits and sample applications for starting ASP.NET MVC proj- ects (as well as ASP.NET Web Forms starter kits). The options include ■ Kigg Starter Kit—a Digg-like application ■ Contact Manager Sample Application ■ Storefront Starter Kit Although the starter kits are quite basic, you should also check out more complete starter kits like those found at http://CommunityForMvc.net. This site contains a bare-bones template as well as one complete with MvcContrib, StructureMap, NHibernate, NUnit, NAnt, AutoMapper, Tarantino, Naak, NBehave, Rhino Mocks, WatiN, Gallio, Castle, 7zip, and more. If you’re new to .NET development in general, you should first become familiar with Microsoft’s default template. Then use a more robust starter kit or sample application provided by the community to have a better jumping-off point. When you have mastered the framework, think about contributing your own starter kits. Figure 1.2 The MVC Web Application project is a project template added to the C# and VB.NET sections of the New Project dialog. It’s only available when you have .NET Framework 3.5 selected as the target framework.
  • 39. 6 CHAPTER 1 Getting started with the ASP.NET MVC Framework Figure 1.3 The default structure for a web application project using the ASP.NET MVC Framework uses conventions for the placement of files. The first thing to notice is that in contrast to the very sparse structure of a default Web Forms project template, the default MVC tem- plate creates several folders: Content, Control- lers, Models, Scripts, and Views. These folders represent part of the MVC application develop- ment conventions, which, if adhered to, can make the experience of developing with the MVC framework a breeze. For now, the most important of these fold- ers to become familiar with are the three which have been named after their MVC pattern coun- terparts (the Model, View, and Controller fold- ers). As you’d expect, the purpose of each of these folders is to provide logical separation of the three MVC concerns, as well as to tap into a nice feature of Visual Studio that will automati- cally namespace any class created within a folder with that folder’s name. The Controllers folder is probably the least interesting. The folder should contain only classes which are to be used as controllers, or base classes and interfaces that controllers might inherit from. The Views folder is special because it will contain code that will probably be the most familiar to Web Forms developers. The Views folder contains the aspx (views), ascx (partial views), and master pages used to present the data. Typically you’ll have a folder inside the Views folder for each controller which will contain views intended to be used specifically by that controller, as well as a Shared folder to contain shared views. The Happy Path ASP.NET MVC developers (and developers using other convention-centric frame- works) will often mention the Happy Path. This refers to the notion that following the MVC framework’s conventions will make the developer’s experience both enjoyable and relatively painless. The MVC framework does not require you to adhere to any particular convention, but the farther you stray from the Happy Path the greater the effort will be required by the developer. The MvcContrib project enhances the path, and you’ll certainly find ways to enhance it in your system. Staying on the path gains you a great deal in consistency.
  • 40. 7 Picking apart the default application For most nontrivial projects, you probably won’t place your models in the Models folder. Generally speaking it’s a best practice to keep your domain model in a separate project so that other applications can use it without taking a dependency on your MVC application. We recommend that you put only presentation concerns in the Web Application project. In the default project, you may be familiar with the Default.aspx file that is pro- vided for you, and we’ll discuss shortly why it is there. First, we must understand the concept of a route. 1.1.2 Your first routes Routes will be discussed in great detail in chapter 5; however, you should be aware of some route basics to move through this section. Although Web Forms mandated a strict convention for URLs, the MVC framework provides a mechanism to allow devel- opers to handcraft URLs, and have them map automatically to an object in the system that can handle the incoming web request. Routing was added to ASP.NET in the .NET Framework 3.5 Service Pack 1 release, and is available to all ASP.NET applications. The Global.asax.cs file contains basic routes that are provided with the MVC Web Appli- cation project to help you get started. Before continuing, we should define a route. A route is the complete definition for how to dispatch a web request to a control- ler, usually using the System.Web.Mvc.MvcRouteHandler. In the past we have had little control over message dispatching without resorting to external tools like ISAPI filters or carefully crafted HttpModules for URL rewriting. With Web Forms, the URL of the web request was tightly coupled to the location of the page handling the request. If the page was named Foo.aspx in a folder named Samples, the URL was sure to be something like http://MvcContrib.org/Samples/Foo.aspx. Many teams have resorted to URL rewriting to wrangle some control over the URLs and how they are produced. With the ASP.NET MVC Framework, and ASP.NET 3.5 SP1 in general, routes are first-class citizens that can be managed directly in the web application. We start with defining how we want our URLs structured. The project template gives us a few routes to start, as shown in listing 1.1. using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Ch1GettingStarted { public class MvcApplication : HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", "{controller}/{action}/{id}", Listing 1.1 Default routes for a new project Route name URL with parameters
  • 41. 8 CHAPTER 1 Getting started with the ASP.NET MVC Framework new {controller = "Home", action = "Index", id = ""} ); } protected void Application_Start () { RegisterRoutes(RouteTable.Routes); } } } Routes must be defined before any request can be received by the application, so the project template adds the routes to the Application_Start method in the Global. asax.cs file. Later in the book, you’ll see that we do not leave the routes in this location except for the most trivial of web applications. NOTE We’ll follow long-standing best practices of separation of concerns (SoC) and the single responsibility principle, or SRP, by moving the routes to a dedi- cated location separated by an interface. We’ll go further into these principles later, but, in short, the responsibility (or concern) of the Application_Start method is to kick off operations that must happen at the beginning of the application’s life. The responsible approach is to avoid performing every bit of work that must happen on start. Any opera- tions that must happen when the application starts should reside in sepa- rate classes and merely be called in the appropriate order in the Application_Start method. Note that the URL portion of the route is simply a matching mecha- nism for the request. If the URL matches a particular route, then we spec- ify what controller should handle the request and what action method should execute. You can create as many routes as you like, but one route is provided for you. This route has the template, {controller}/ {action}/{id}. The route with the template {controller}/{action}/{id} is a generic one and can be used for many, many different web requests. Tokens are denoted by the inclusion of {braces}, and the word enclosed in braces matches a value the MVC framework understands. The most common val- ues that we’ll be interested in are controller and action. The controller route value is a special value that the System.Web.Mvc. MvcHandler class uses to call into the IControllerFactory interface. This is also the route we’ll be using for the rest of the chapter, so we’ll be content with a URL in the form of http://MvcContrib.org/controller- name/actionname. The basic route handler is an instance of IRoute- Handler named MvcRouteHandler. We have complete control and could provide our own implementation of IRouteHandler if we wished, but we’ll save that for a later chapter. Before we spin up our first controller, let’s examine what is different about the web.config file in an MVC Web Application project. The differences are easy to spot. Parameter defaults
  • 42. 9 Picking apart the default application Just look for “routing” or “MVC.” One difference we see is that a new IHttpModule is registered in the config file. We see the UrlRoutingModule in listing 1.2. <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> The UrlRoutingModule evaluates a request and checks if it matches a route that is stored in the RouteTable. If the route matches, it overrides the default handler (IHttpHandler) for the request so that the MVC framework handles the request. We’re going to examine our first controller as a means to handle a route for the URL /home. In the next section you’ll see how all the pieces of the starter project fit together. 1.1.3 Running with the starter project We’re going to move through the starter project quickly looking at each piece of provided code. Each serves as an example of how to fit code together when writing an application with the presentation layer powered by the ASP.NET MVC Framework. Before look- ing at code, run the web application by pressing CTRL + F5, and you should see a screen that resembles figure 1.4. The starter project includes some navigation, a Log On, and content. The CSS provides simple formatting on top of XHTML. Notice the URL in the address bar is /. "/home" also will bring up the same page since our route specifies “home” as the default controller. This URL does not have an extension, so if you’re planning on running your application on IIS 6, you must either add a wildcard mapping or install an ISAPI filter that provides this functionality. Deployment to IIS 6 will be covered in more detail in chapter 10. Since you’re familiar with the ASP.NET request pipeline, we’ll briefly move through how this request makes its way to an ASP.NET MVC controller. The following outlines how the request moves through ASP.NET, to the controller, and through the view: 1 Request comes in to /Home. 2 IIS determines the request should be handled by ASP.NET. 3 ASP.NET gives all HttpModules a chance to modify the request. 4 The UrlRoutingModule determines that the URL matches a route configured in the application. Listing 1.2 Unique addition to the web.config file Figure 1.4 The starter project comes with a basic layout and CSS.
  • 43. 10 CHAPTER 1 Getting started with the ASP.NET MVC Framework 5 The UrlRoutingModule gets the appropriate IHttpHandler from the IRoute- Handler that is used in the matching route (most often, MvcRouteHandler) as the handler for the request. 6 The MvcRouteHandler constructs and returns MvcHandler. 7 The MvcHandler, which implements IHttpHandler, executes ProcessRequest. 8 The MvcHandler uses IControllerFactory to obtain an instance of ICon- troller using the "controller" to route data from the route {controller}/ {action}/{id}. 9 The HomeController is found, and its Execute method is invoked. 10 The HomeController invokes the Index action. 11 The Index action adds objects to the ViewData dictionary. 12 The HomeController invokes the ActionResult returned from the action, which renders a view. 13 The Index view in the Views folder displays the objects in ViewData. 14 The view, derived from System.Web.Mvc.ViewPage, executes its Process- Request method. 15 ASP.NET renders the response to the browser. These steps represent the simplified life of a request handled by the ASP.NET MVC Framework. If you’re curious about the details, you can browse the source code at http://www.codeplex.com/aspnet. The 15 steps are sufficient for understanding how to write code based on the ASP.NET MVC Framework, and most of the time you’ll need to pay attention only to the controller and the view. You have already seen the route used in the starter project. Let’s look at the HomeController, shown in listing 1.3. using System.Web.Mvc; namespace Ch1GettingStarted.Controllers { [HandleError] public class HomeController : Controller { public ActionResult Index() { ViewData ["Message"] = "Welcome to ASP.NET MVC!"; return View(); } public ActionResult About() { return View(); } } } Notice how simple the controller is. There is not much generated code to wade through, and each action method returns an object derived from ActionResult. This Listing 1.3 The HomeController B Default action for controller C Return default view for action Another action method
  • 44. 11 Picking apart the default application controller derives from System.Web.Mvc.Controller B. You’ll probably find this base class adequate, but there are others to choose from in the MvcContrib project, and as time goes on, the community will likely make many more available. It also may be a good practice to create your own layer supertype to use in your application. Inside each action method, you’ll typically put some objects into a dictionary called ViewData C. This dictionary will be passed to the view upon rendering. The controller can provide any objects the view requires in this ViewData dictionary; the primary object the view will render should be assigned to the ViewData’s Model property. This can be done automatically by passing the object into the controller’s View() method. In the starter project, the objects are simple strings, but in your application, you’ll use more complex objects like those in figure 1.5. Each default action returns the result of the View()method,whichreturnsaSystem.Web.Mvc. ViewResult object. This ActionResult subclass willlikelybeacommonresultgiventhatyourappli- cations will have many screens. In some cases, you may use the other ActionResult types as shown in figure 1.5. Your controller action can return any type. The Controller base class will call ToString() on your object and return that string in a ContentResult object. Next, let’s look at the view shown in listing 1.4, which can be found in the project in the following path: /Views/Home/ Index.aspx. <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" ➥ runat="server"> Home Page </asp:Content> <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" ➥ runat="server"> <h2><%= Html.Encode(ViewData ["Message"]) %></h2> <p> To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>. </p> </asp:Content> The view shown in listing 1.4 is the one rendered in the browser screenshot shown in figure 1.4. With the MVC framework, markup files do not use a code-behind file. Since the view uses the Web Forms templating engine, you could use it, but by default just a simple markup file is generated. Listing 1.4 A simple view Figure 1.5 Classes that derive from ActionResult. This screenshot is from Red Gate’s .Net Reflector.
  • 45. 12 CHAPTER 1 Getting started with the ASP.NET MVC Framework This view uses a master page, as you can see in the MasterPageFile attribute in the Page directive. The master can be specified by the controller for compatibility with many view engines, but some view engines support the view specifying the layout, which is the case with the Web Forms view engine, the default view engine that ships with the MVC framework. NOTE: A ViewResult leverages the IViewEngine interface, which is an abstrac- tion that allows the usage of any mechanism for rendering a view. View engines will be covered in more depth later, but some alternatives can be found in the MvcContrib open source project. In the body of this view, the server-side tags are pulling objects out of ViewData and rendering them in line with HTML. The responsibility of the view is to take objects in ViewData and render them for consumption by the user. The view does not decide what to render, only how to render. The controller has already decided what needs to be rendered. In listing 1.5, examine the code of the layout. You immediately see that it’s a plain master page, not much different from those found in Web Forms. The difference is that master pages in MVC projects do not need to use code-behind files. <%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/ TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/> <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /> </title> <link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="page"> <div id="header"> <div id="title"> <h1>My MVC Application</h1> </div> <div id="logindisplay"> <% Html.RenderPartial("LogOnUserControl"); %> </div> <div id="menucontainer"> <ul id="menu"> <li><%= Html.ActionLink("Home", "Index", "Home")%></li> <li><%= Html.ActionLink("About", "About", "Home")%></li> </ul> </div> </div> <div id="main"> <asp:ContentPlaceHolder ID="MainContent" runat="server" /> Listing 1.5 The starter project master page Render another view Render hyperlinks
  • 46. 13 Picking apart the default application <div id="footer"> </div> </div> </div> </body> </html> The master page here is in charge of navigation. It uses view helpers (Html.Action- Link in this case) to render the links. View helpers are available for most common dynamic needs and for all form elements. More view helpers are available in Mvc- Contrib, and third-party component vendors will not be far behind in offering com- mercial view helpers. Now that you have seen how the code in the starter project fits together, let’s see how to test the controller code. View code will still need to be tested with a tool like Selenium, Watir, or WatiN, but controller code can easily be test-driven since it’s decoupled from the view and the ASP.NET runtime. When you start a new MVC proj- ect, a dialog will ask you which unit testing framework you’d like to use. If you’re using Visual Studio 2008 Professional then Visual Studio Unit Test will already be in the list and selected. Most common unit testing frameworks have templates that show up in the list when they are installed. For now we’ll look at using MSTest (Visual Studio Unit Test), but we recommend using NUnit. If you’re just start- ing out in automated testing, any mainstream framework will do. Listing 1.6 shows an MSTest test method included in the default test project template. using System.Web.Mvc; using Ch1GettingStarted.Controllers; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Ch1GettingStarted.Tests.Controllers { [TestClass] public class HomeControllerTest { [TestMethod] public void Index() { HomeController controller = new HomeController(); ViewResult result = controller.Index() as ViewResult; ViewDataDictionary viewData = result.ViewData; Assert.AreEqual("Welcome to ASP.NET MVC!",viewData["Message"]); } } } Believe it or not, we have walked through the complete ASP.NET starter project, and you now know the basics of the new framework. Obviously, we’ll be moving into more com- plex topics throughout this book, and if any topic along the way does not sink in com- pletely, please crack open Visual Studio and poke around while reading. Working with Listing 1.6 The unit test for the Index action
  • 47. 14 CHAPTER 1 Getting started with the ASP.NET MVC Framework the code directly, along with reading this text, will give you a solid understanding of this technology. In fact, now is a great time to download the code samples for this book and open your IDE default application. 1.2 Your first ASP.NET MVC controller from scratch Look at listing 1.7 to understand how a web request is processed by the controller. Note the only requirement is to implement the IController interface. using System; using System.Web.Mvc; using System.Web.Routing; namespace MvcApplication.Controllers { public class HelloWorld1Controller : IController { public void Execute(RequestContext requestContext) { requestContext.HttpContext.Response.Write( "<h1>Hello World1</h1>"); } } } As with everything in the ASP.NET MVC Framework, there is very little the developer must do to create custom functionality. In the case of the controller, the only—I will say it again—the only requirement is that the class implement the IController inter- face B. This interface only requires that you implement a single method: Execute. How you handle the request is entirely up to you. In the controller in listing 1.7, we’re intentionally violating all principles of sensible programming as well as the Law of Demeter in order to get the message “Hello World” written out to the screen as quickly as possible. In this case, I’ve chosen not to make any use of a view. Rather, I’m formu- lating incomplete HTML markup and directing it to the response stream. We’ll run the sample and note the output in figure 1.6. In the code solution that comes with the book, you can find HelloWorld1ControllerTester that illustrates how you’d unit test a simple controller like this. Listing 1.7 Our first controller B Figure 1.6 Our web application running in the browser. Note the simple URL and the absence of .aspx.
  • 48. 15 Your first ASP.NET MVC controller from scratch Listing 1.7 shows the absolute and complete power you have when creating a controller class. It’s very important to have complete control; however, most of the time, we’re working in a handful of scenarios that repeat over and over. For these scenarios, the product provides a base class that gives extra functionality. The base class for these com- mon controllers is System.Web.Mvc.Controller. It implements the Execute method for us and uses the route values to call different action methods depending on the URL and the route defaults. NOTE System.Web.Mvc.Controller is only one option to choose as a base class for your controllers. As mentioned earlier, it’s often appropriate to cre- ate your own layer supertype for all of your controllers. This type can inherit from System.Web.Mvc.Controller, implement IController, or derive from any other controller base class. Our first use of the Controller base class will need only one action method, and we’ll go with the convention for the default action and call it Index. Observe in listing 1.8 what our controller looks like while we leverage the Controller base class. This base class implements the IController interface for us and provides the capability of invoking action methods based on the current Route. using System.Web.Mvc; namespace MvcApplication.Controllers { public class HelloWorld2Controller : Controller { public string Index() { return "<h1>Hello World2</h1>"; } } } The public Index action method is all that is necessary for this controller to be web-call- able. Simple content action methods need not return ActionResult. Returning any other type will result in that object being rendered as content to the response stream. If we point our browser to /HelloWorld2, we’ll see that our controller sends the same response to the browser as shown in figure 1.7: Listing 1.8 Using the Controller base class Inherit from Controller Figure 1.7 The web page has the same output as before. The end result is the same even though the controller implemen- tation has evolved.
  • 49. 16 CHAPTER 1 Getting started with the ASP.NET MVC Framework Now that we know how to craft a controller, we’ll explore our first view. 1.3 Our first view Recall that the ASP.NET MVC Framework uses a convention for locating views. The convention is to find a .aspx file in a directory tree that matches /Views/controller- name/actionname.aspx. In our next example, we’ll modify our controller by calling a method on the Controller base class called View(). We’ll set the model, which is a string with the text “Hello World”, to an entry in the ViewDataDictionary object on the ViewData property of the Controller base class. This ViewDataDictionary instance will be forwarded to the view. Although ViewData is a ViewDataDictionary we recommend you depend only on the IDictionary<string, object> interface if you’re replacing the view engine. View engines will be discussed in more detail in chapter 4. In listing 1.9, we see that our action returns ActionResult instead of string. After an action method returns, the ActionResult executes to perform the appropriate behavior, which is rendering a view in this case. Examine listing 1.9 for the current implementation of our controller. ViewData contains the object that will be forwarded on to the view. The View() method also supports passing a single object to the view that is then accessible via ViewData.Model, which we’ll explore later. using System.Web.Mvc; namespace MvcApplication.Controllers { public class HelloWorld3Controller : Controller { public ActionResult Index() { ViewData.Add("text", "Hello World3"); return View(); } } } If you’re following along with this example, you’ll want to create a HelloWorld3 folder inside /Views in your project as shown in figure 1.8. Next, add a view to the project inside /Views/ Helloworld3. You can use the New Item dialog for the project and select the MVC View Page; a quicker way is to use the context menu (right click) off of the action and select Add View… as shown in figure 1.9. This tool will create a view with the proper name inside the proper folder. Your project should now look similar to fig- ure 1.8. Our new view, Index.aspx, resides in the HelloWorld3 folder. Listing 1.9 Using a view to render the model Add objects to ViewData Figure 1.8 The proper location of the HelloWorld3 folder is inside the /Views folder. The default view factory uses this convention. You can override this behavior if you wish.
  • 50. Other documents randomly have different content
  • 51. Olaf’s Grievances. scandalize simple folk by the impudence which leads them to aim at the abolition of the ancient usages of the Church; and I think further that they have cherished the purpose of giving a lesson to me and my government.’[477] The prince, far from taking a lesson from another, gave one, and that sharply, to the first preacher of the capital. These two men were both of a noble nature. In each were greatness, devotedness, activity, and a strong love of good. But each had also a fault which laid them open to the risk of a rude collision with each other; and one shock of this kind might overthrow the weaker. Gustavus would dictate as law whatever seemed to him good and wise, and he did not intend to allow any resistance. He placed great confidence in any man who showed himself worthy of it; and of this he had given striking proofs to the two brothers Petri. He did not easily withdraw his favor; but once withdrawn, it was impossible to regain it. Olaf, on his side, endowed with a spirit of integrity and with a sincere and living faith, had a vivacity of temperament which prevented him from pondering the path of his feet. He could not endure contradiction, he could hardly forget an offence, and he was too prone to attribute malevolent motives to his adversaries. He not only believed that the king intended to destroy the liberty of the Church (which was the fact), but also that his obstinate maintenance of Romish customs among the people would throw them back again into the Romish apostasy. He began loudly to complain of Gustavus. He said to all about him that the king was completely changed, and certainly for the worse. He did not refrain from speaking in this manner even in the presence of flatterers of Gustavus. The enemies of the reformer hastened to take advantage of this. They reported to the king what they had heard Olaf say, adding to it exaggerations of their own invention.[478] Their one object was to stir up hatred, and that implacable, between the king and the reformer. They did not gain their end at the first stroke; but a change was gradually wrought in the relations between these two men, both so necessary to Sweden.
  • 52. The king manifested to Olaf his unconcern by his manner and his words. He saw him much less frequently; and when he did send for him, there was a reserve in his reception which struck the reformer. Frequently when Olaf requested to see the king, the latter refused to admit him; or if he did receive him, business was despatched as speedily as possible, as if his only care was to get rid of him. This coolness, while it greatly grieved the sincere friends of the Gospel, rejoiced its adversaries; and on both sides the people were wondering, some with a sense of alarm, others with secret but deep joy, whether Gustavus in thus gradually estranging himself from the reformer was not at the same time making friends with the pope, and whether a few steps more would not precipitate him into the abyss. Olaf himself, who while complaining of Gustavus had nevertheless up to this time entertained no doubt of his good intentions, now took offence, and resolved to avail himself of his rights as a minister of the Word of God. Ought he to conceal the truth because it was to a prince that it must be spoken? Did not Elijah rebuke Ahab, and John the Baptist Herod? The feeling which blinded him did not allow him to apprehend the important difference existing between a Gustavus and an Ahab. An obvious fault of the king had often struck him. The habit of swearing in a fit of anger was very common at the court and in the town, and Gustavus set the example. Olaf, pained to hear the name of God thus taken in vain, preached against the sin. He did not hesitate, at the close of his sermon, to designate the king as setting the example of swearing. He even had his discourse printed; and letting loose his displeasure, he complained loudly of the obstacles which the king placed in the way of a thorough reformation. The young pastors, encouraged by the example of their chief, went further than he did. They complained of the commands which the king had given them, and gave free vent to their indignation against a despotism which was, in their view, an attempt to violate the rights of the Word of God and of Christian freedom. It was a serious matter, and Gustavus was much moved by it. He resolved to appeal to the archbishop. The primate, more temperate
  • 53. The Mock Suns. than his brother, confined himself to the duties of his calling. He was never seen either in places of amusement or at the court, which his predecessors used frequently to visit; but he was always at work in his diocese. In consequence of the death of the queen, he had gone at the king’s call to Stockholm, to marry him to his second wife, and had immediately returned to Upsala to devote himself to his work. Gustavus esteemed Lawrence; but he was, nevertheless, somewhat out of temper with him, because he knew that at bottom he shared his brother’s sentiments. To him, in his capacity of archbishop, the king addressed his mandate, in September, 1539. ‘We had expected of you and of your brother,’ said Gustavus, ‘more moderation and more assistance in matters of religion. True, I do not know how a sermon ought to be composed, but still I will tell you that preachers ought to confine themselves to setting forth the essence of religion without setting themselves up against ancient customs. You wrote me word that sermons were being preached at Upsala on brotherly love, on the life acceptable to God, on patience in affliction, and on other Christian virtues. Very good: see to it that similar sermons are preached throughout the kingdom. Christ and Paul taught obedience to the higher powers; but from the pulpits of Sweden are too often heard declamations against tyranny, and insulting language against the authorities. I am accused, abuses which are complained of are imputed to me, and these insults are published by the press. Holy Scripture teaches us that a minister ought to exhort his hearers to seek after sanctification. If people had any real grounds of complaint against my government, why not make them known to me privately instead of publishing them before the whole congregation?‘[479] This letter, addressed to the archbishop of Upsala, instead of soothing the Stockholm minister, irritated him and inflamed still more his ardent zeal. A circumstance which had little connection with the religious interests of Sweden, convinced him that the time was come to denounce the judgments of God. Olaf, in common with some of the most enlightened men of his time, among others Melanchthon, believed in astrological predictions. Seven or eight mock suns, reflecting in the
  • 54. clouds the image of the sun, appeared over Stockholm at this time. The sun was of course Gustavus, and the mock suns were so many pretenders who were on the point of appearing around the king, one or other of whom would take his place. ‘It is a token of God’s anger and of the chastisement which is at hand,’ exclaimed Olaf in his pulpit. ‘Punishment must come, for the powers that be have fallen into error.’ The unfortunate Olaf did more. Exasperated by the part which the king was taking in the government of the Church, he caused these mock suns to be painted on a canvas, and this he hung up in the church, in order that all might satisfy themselves that God condemned the government and that His judgments were near.[480] This proceeding was even more ridiculous than blameworthy, but it was both. It took place, undoubtedly, after the king in his capacity of Summus Episcopus had addressed the letter to the archbishop; for although he spoke in it of the sermons on swearing, there is no reference to that on the mock suns, which was, moreover, by far the most serious affair. The anger of Gustavus against Olaf was now at its height. His enemies gladly seized the weapon with which by his mistakes he furnished them against himself; and already they insulted him with their looks. A storm was gathering against the reformer; and Anderson, whose elevation and influence had made many jealous, was to fall with his friend. These two personages being manifestly in disgrace, the number of those who contributed to their ruin was daily increasing; and it seemed as though nothing short of the death of the objects of their hatred could satisfy them. All this would have been without effect if Gustavus had continued to protect the liberty of the reformers. But he thought (this is at least our opinion) that he might take advantage of the animosity existing between the two parties for maintaining his own universal and absolute authority. Olaf was blinded by excess of zeal, and Anderson did not sufficiently subordinate the interests of religion to those of politics. A sharp lesson must be given to each of them. Olaf was accused of having delivered seditious sermons, and of having
  • 55. Charges Against Olaf And Anderson. censured in a historical work the ancestors of the king. This was not enough. Some still more serious charge must be made. For this they went back four years (1536), and it was given out that the project, formed by the German inhabitants of Stockholm, of favoring the attack by the Hanse Towns, had been confided to Olaf under the seal of confession—this institution was still in existence—and that he had not made it known. Even if this supposition had any foundation, was it not truer still that the hostility of the Germans was universally known, and especially by the vigilant Gustavus? But, in fact, there was little more in the case than rumors, no attempt whatever at execution of the plan having ever been made. To suppose that Olaf had intended to injure the king, his own benefactor and the saviour of Sweden, is a senseless hypothesis. Many other persons in Stockholm had learnt as much of the matter and more than he had. But the enemies of the Reformation wanted to get rid of the reformer; they must have some pretext, and this appeared to be sufficient. People asked, indeed, why Olaf had not been prosecuted for this offence four years before, and why since that time no inquiry had been set on foot about it. But all improbabilities were passed over. All the passions of men combined against Olaf. Men of lower degree felt the hatred of envy caused by the elevation of the son of the ironmaster of Orebro. The great felt the hatred of pride, a hatred which is seldom appeased. Worldly and bad men, such as were not wanting at the court, felt that irreconcilable hatred which is cherished against those who declare war on vice and worldliness. The king commanded that Olaf as well as Anderson should be brought to trial. The writer who recounts, in a not very authentic manner, the alleged offence of the reformers, was a zealous Roman Catholic, and besides this a very credulous man.[481] The archives of Lübeck, the town which played the leading part in the attack of which it was alleged that Olaf was an accomplice, are very complete for the history of this period; but they do not contain the slightest trace of any proceeding of the kind. [482] Men of peremptory character resemble each other; and,
  • 56. although Gustavus Vasa was infinitely superior to Henry VIII., the proceedings against Olaf and Anderson remind us of those instituted by the king of England against his wives, his most devoted ministers, and his best friends. The same court influences, and the same pliability on the part of the judges were found in both cases; and, by a stroke which recalled the Tudor sovereign, the king insisted that the archbishop should sit as a judge at the trial of his brother. Olaf and Anderson were condemned to death in the spring of 1540. This was paying rather dear for the folly of the mock suns. ‘Simplicity,’ it is said, ‘is better than jesting’; and a simple and credulous proceeding often disarms the man who has a right to complain of it. Olaf had been simple and credulous, but his foolishness did not disarm the king. The sentence which filled the ultramontanes with joy threw consternation among the evangelical Christians, and especially among the parishioners of Olaf. The man who had so often consoled and exhorted them was to be smitten like a criminal. They could not bear to think of it. They remembered all the services which he had rendered them, and, what does not often happen in this world, they were grateful. They therefore bestirred themselves, interceded in behalf of their pastor, and offered to pay a ransom for his life. The king did not push matters to extremities, but granted a pardon. Perhaps his only intention had been to inspire fear in those who assumed to set limits to his power. The townsmen of Stockholm paid for their pastor fifty Hungarian florins. Anderson also saved his life, but by a payment out of his own purse. These pecuniary penalties contributed to keep people in mind that the king was not to be contradicted. The exaction of these sums for the ransom from the scaffold of the two men who had done the most good to Sweden did no honor to Gustavus. But he appears to have thought that strong measures were necessary for the purpose of maintaining himself on the throne to which he had been elevated. It was part of his system to strike and to strike hard.
  • 57. Olaf’s Sermon. Olaf subsequently resumed his functions as preacher at the cathedral. Was not the permission to reappear in the pulpit an acknowledgment of his innocence? On this occasion he delivered an affecting discourse by which the whole congregation was moved. He understood the lesson which Gustavus had given him, and acknowledged that henceforth resistance to the king’s authority in the church was useless. This resistance might sometimes have been not very intelligent, but it was always sincere and well meant. He could not begin again either to preach the Gospel or to reform Sweden unless he submitted. This, therefore, he did. Before every thing the Gospel must advance. The king did not conceal his intention of governing the Church as well as the State. He said to his subjects, ‘Take care of your houses, your fields, your pastures, your wives and your children, but set no bounds to our authority either in the government or in religion.[483] It belongs to us on the part of God, according to the principles of justice and all the laws of nature, as a Christian king to give you rules and commandments; so that if you do not wish to suffer our chastisement and our wrath, you must obey our royal commands in things spiritual as well as in things temporal.’ Olaf had learnt by experience that the wrath of a king is as the roaring of a lion. He had paid his debt to the liberty of the church. Henceforth he bowed his head; he gave himself wholly up to his ministry; to instruct, to console, to confirm, to guide, these tasks were his life, and in the discharge of his duty he won high esteem. As for Anderson, he never recovered from the blow which had fallen upon him. This fine genius was extinguished. He who had done so much towards giving a durable life to the church and to the State went slowly down to the grave, overwhelmed with sorrow. A strange drama, in which the actors, all in the main honest, all friends of justice, were carried away by diverse passions, the passion for power and the passion for liberty, and inflicted on each other terrible blows, instead of advancing together in peace towards the goal which both alike had in view.
  • 58. George Normann. Gustavus had won the victory. Olaf was not the only one who gave way. The blow which had fallen upon Olaf alarmed the other evangelical ministers so much that they abandoned the thought of taking any part in the control of the church, and left it all to the king. This pope was satisfied. The mock suns had disappeared one after another, and the sun left alone shone out in all his glory. Gustavus, having thus broken down what threatened to be an obstacle in his way, took up his position as absolute monarch in the Church and in the State. In 1540 he obtained at Orebro a declaration that the throne should be hereditary; and taking in hand the ecclesiastical government he named a council of religion under the presidency of his superintendent-general, who was strictly speaking minister of worship. The king had engaged, as governor to his sons, George Normann, a Pomeranian gentleman, who had studied successfully at Wittenberg, and had come into Sweden with testimonials from Luther and Melanchthon. ‘He is a man of holy life,’ Luther had written to Gustavus Vasa, ‘modest, sincere, and learned, thoroughly competent to be tutor to a king’s son.[484] I recommend him cordially to your majesty.’ Luther, however, aimed at more than the education of the prince royal. Having had an opportunity of conversing with an envoy of the king, Nicholas, a master of arts, he wrote to Gustavus —‘May Christ, who has begun his work by your royal majesty, deign greatly to extend it, so that throughout your kingdom,[485] and especially in the cathedral churches, schools may be established for training young men for the evangelical ministry. Herein consists the highest duty of kings who, while engaged in political government, are friendly to Christian piety. In this respect your majesty has the reputation of surpassing all others, illustrious king! and we pray the Lord to govern by his spirit the heart of your majesty.’ Along with George Normann, Luther sent a young scholar, named Michael Agricola, whose learning, genius, and moral character he extols. In conclusion he says—‘I pray that Christ himself may bring forth much fruit by means of these two men; for it is he who through your majesty calls them and assigns them their duties. May the Father of
  • 59. mercies abundantly bless, by his Holy Spirit, all the designs and all the works of your royal majesty.’[486] It seems as if Luther had some fear that Gustavus might monopolize too much the government of the Church. In his view it is Christ who governs it, who calls and appoints his laborers. Gustavus appreciated the abilities and the character of Normann, and saw in him an honorable but yielding man, at whose hands he would not encounter the resistance which Olaf had offered. The bishops gave him some uneasiness, and as he did not venture to suppress them, he resolved to neutralize their influence by placing the protégé of the Wittenberg reformer above all the clergy, including the bishops and even the archbishop. While allowing the episcopal order to subsist for form’s sake, he at the same time introduced a semblance of the presbyterian order. In 1540 he appointed in all the provinces conservators, counsellors of religion, and seniors or elders who under the presidency of the superintendent were to administer ecclesiastical affairs and make regular visitations in the dioceses. No change might be made or even proposed in the Church without the express permission of the king. The opposition of Olaf and other ministers to certain remains of popery was not, however, without effect. Gustavus abolished them. But this semi-episcopal and semi-presbyterian constitution could never be got to work perfectly; and at a later time fortunate circumstances restored to the Swedish Church a more independent standing. Gustavus continued to have at heart the serious fulfilment of the functions of supreme bishop. He made laws for the frequenting of the religious assemblies, for the observance of the rules prescribing a decorous behavior in the church, for the suppression of immorality both among the laity and among the ecclesiastics, for the improvement of teaching and for the spread of civilization and culture among the people. Desirous of seeing the extension of the kingdom of God, he sent missionaries into Lapland. In Sweden likewise he set the inspired Word above every thing. ‘Thou doest well,’ he wrote to one of his sons, ‘to read the writings of the ancients and to see how the world was then governed; but do
  • 60. Excuses For Severity. not give these the preference over the Word of God. In this is found true instruction and reasonable morals; and from it we learn the best mode of governing.’ This zeal for good did not prevent him from hitting hard when he thought he saw any thing amiss. He could be calm, gentle, and tolerant, but also earnest, terrible, and swift as a thunderbolt. If he perceived any opposition he struck energetically. ‘It is not right,’ he said one day, ‘that the bishop of Strengnaes should dwell in a stone house. It appears to me that a wooden house might suffice for a servant of him who made himself poor.’ The bishop boldly answered—‘It is doubtless in the same chapter of Holy Scripture that it is said that to the king tithe ought to be paid.’ The bishop’s reply having offended the king, he was not slow to show his displeasure. The marriage of the bishop was at this time being celebrated. It was his wedding- day, and there was a large company and a grand feast in the stone house. Gustavus unhesitatingly sent his sergeants in the very midst of the rejoicings, with orders to carry off the bishop from the marriage table, paying no regard to the general alarm, and he cast him into prison. His benefice was given to another. The contemporaries of Gustavus might reproach him, and with good reason, for his severity; and yet this seems moderation in comparison with the ways of Henry VIII., Mary Tudor, Francis I., Henry II., Charles IX., and with those of his predecessor Christian II. ‘I am called,’ he said, ‘a harsh monarch; but the days will come when I shall be regretted.’[487] He had indeed other qualities which made people forget his severity. The beauty of his person predisposed men in his favor, and the eloquence of his speech carried away all with whom he had to do. But there are other considerations which although they do not justify his rigorous measures, explain them. The kingdom of Christ not being of this world ought not to be governed by kings and by their secretaries of state. This principle once admitted, there are three remarks to make: The development
  • 61. of Christian civilization was not sufficiently advanced in the sixteenth century for a recognition of the independence of the two powers. Catholicism was still so powerful in Sweden that nothing short of the authority of such a king as Gustavus could secure to the Gospel and to its disciples the liberty which they needed. Lastly, if Gustavus was wrong in assuming, as so many other princes did, the episcopal office in the Church, he did at least discharge its duties conscientiously. In 1537 the king had received deputies from the elector of Saxony, the landgrave of Hesse, and the Protestant towns, who entreated him to unite with the evangelical churches of Germany.[488] Gustavus had promised to do all that might be in his power for the good of their confederation. In 1546 he was formally asked to enter into the league of Smalcalde; but this he declined to do. The Confession of Augsburg was not accepted in his lifetime. It was only after many vicissitudes that Sweden was induced to place itself under this flag.
  • 62. CHAPTER XI. THE SONS OF GUSTAVUS VASA. (1560-1593.) The transformation effected by the Gospel in Sweden during the reign of Gustavus Vasa was incomplete. The whole lump was not leavened. Many of those who received the Reformation did not understand it; and a very large number of Swedes had no wish for it. This state of things, and the vexations which the king’s sons caused him, saddened his old age. At the beginning of the year 1560, the king, feeling ill, convoked the Diet. It met on the 16th of June, and he appeared and took his seat in it on the 25th, having beside him his sons Erick, John, and Magnus, and on his knee his youngest son Charles. He spoke, calling to mind the deliverance which had been granted to Sweden forty years before; and this he attributed to the help of God. ‘What was I that I should rise up against a powerful ruler, king of three realms, and the ally of the mighty emperor Charles the Fifth, and of the greatest princes of Germany? Assuredly it was God’s doing. And now, when the toils and pains of a troubled reign of forty years are bringing down my gray hairs to the grave, I can say, with King David, that God took me from the sheepcote and from following the sheep to be ruler over his people.’ Tears stifled his voice. After a pause he resumed—‘I had certainly no anticipation of so high an honor when I was wandering about in the woods and on the mountains to escape from the sword of my enemies who thirsted for my blood. But blessing and mercy have been richly bestowed on me by the manifestation of the true Word of God. May we never abandon it! I do not shrink, however, from confessing my faults. I entreat my faithful subjects to pardon the weakness and the failures which have been observed in my
  • 63. Retirement Of Gustavus. reign. I know that many persons think that I have been a harsh ruler; but the days are coming in which the sons of Sweden would gladly raise me out of the dust if they could.[489] ‘I feel that I have now but a short time to live; and for this reason I am about to have my will read to you; for I have good reasons for desiring that you should approve it.’ The will was then read, the Diet approved it, and swore that it should be carried out. Then Gustavus rose and thanked the States for making him the founder of the royal house. He resigned the government to his son Erick, exhorted his sons to concord, and stretching out his hand towards the assembly, gave it his blessing, and thus took leave of his people. On the 14th of August Gustavus took to his bed, which he was no more to leave till his death. He said—‘I have been too much occupied with the cares of this world. With all my wealth I could not now buy a remedy which would save my life.’ One of those about him, anxious to know what pain he felt, said to him; using a German mode of speech—‘What do you want?’ He replied—‘The kingdom of heaven, which thou canst not give me.’ His chaplain, in whom he had no great confidence, suggested to him that he should confess his sins. Gustavus, who had confessed them to God as well as to his people, but who had a horror of confession to a priest, replied unceremoniously and indignantly—‘Thinkest thou that I shall confess my sins to thee?’ A little while after, he said to those about him—‘I forgive my enemies, and if I have wronged any man, I pray him to forgive me. I ask this of all.’ He then added—‘Live all of you in concord and in peace.’ During the first three weeks he spoke in a remarkable manner about things temporal and things spiritual. During the last three he kept silence, and was frequently seen raising his hands as if in prayer. After making a profession of his faith, he received the communion of the body and the blood of the Saviour. His son John, who was present, and was the cause of his anxious forebodings, which were too soon realized, having heard the confession of his father, exclaimed—‘I swear to abide by it faithfully.’ The king made a sign for paper to be given him, and he wrote
  • 64. The Two Sons Of Gustavus. —‘Once professed never to be retracted, or a hundred times repeated to....’ His trembling hand could not finish the sentence. After this he remained motionless. The chaplain having begun again his exhortations, one of those in attendance said—‘You speak in vain; His Majesty hears no longer.’ Then the chaplain leaned towards the dying man, and asked him whether his trust was in Jesus Christ, and entreated him, if he heard, to make some sign. To the astonishment of all, the king with a clear voice answered, ‘Yes.’ He then breathed his last. It was eight o’clock in the morning of September 29, 1560.[490] Erick, his eldest son, who was heir to the crown, had hitherto appeared little worthy to wear it. In his character were united the eccentric disposition of his mother,[491] the princess of Saxe-Lauenberg, and his father’s passion. He was rash and presumptuous; and when Gustavus spoke to him by way of exhortation or rebuke he was angry. Gustavus, deeply mourning over him, wrote one day to him—‘For the sake of the sufferings of the Son of God, put an end to this martyrdom which thy aged father endures on thy account.’[492] In his sports he was singular and even cruel. Erick and John, the latter the eldest son of the second wife, were constantly at variance, at first about their games, then about their fiefs, and at last about the crown. Every body knew that the younger of the two brothers was ambitious of the birthright of the elder, and thought that he was entitled to the realm. The father was weighed down with grief on account of these two sons. Erick had not been left without good counsel. A French Protestant, named Denis Burrey (Beurreus), a zealous Calvinist, had succeeded Normann as his governor. In addition to Burrey, another Frenchman, Charles de Mornay, baron of Varennes, was well received at his court. The two Calvinists persuaded Erick to ask for the hand of the Princess Elizabeth, even before she became Queen of England.[493] Duke John exerted all his influence to promote this plan, which, in case it succeeded, might leave to him the crown of Sweden.
  • 65. Disputes About The Supper. Magnificent embassies were sent; John and Erick himself went to England, but the princess never gave him any hope. At the time of the prince’s accession to the throne, the people had some hope of him. The germ at least of great qualities was in him; and his understanding, which was above the average, had been developed by the care of his teachers. He was well acquainted with literature, with mathematics, philosophy, and foreign languages.[494] His figure was well formed; he was a good rider, a good swimmer, a good dancer, and a good soldier. He spoke pleasantly and was agreeable in his intercourse with others. But in the depth of his nature was a temper strange, distrustful, suspicious, and fierce, which might on a sudden display itself in outward acts calculated to excite at once both pity and horror. Burrey, who had been appointed to instruct the prince in letters and in science, was not entrusted with the department of religion. This belonged to the archbishop, Lawrence Petersen, and to the Lutheran ministers named by him. Erick was to be a good Lutheran; but the French Protestant, convinced of the truth of Calvin’s principles, made them known to his pupil. Calvin himself, doubtless through the medium of Burrey, was in correspondence with Gustavus in 1560, towards the close of the king’s life. In Sweden the Calvinists gave especial prominence to the doctrine of the Lord’s Supper. Burrey, who appears to have apprehended the doctrine in the way of logic rather than of spiritual insight, maintained it by syllogisms. He said—‘All who eat the flesh of Christ and drink his blood have eternal life. Now the ungodly have not eternal life. Therefore the ungodly do not eat the flesh of Christ.’[495] The Apostle John says nothing about the corporeal mastication, it but speaks only of the spiritual. Therefore, he recognizes no other mastication but that which is by faith. Christ gives his body and his blood only to those who show forth his death. But the ungodly do not show forth. Therefore he does not give it to them. The Frenchman maintained these doctrines in a Latin work. He had of course a right to do so;
  • 66. but he had no right to attack as he did the archbishop, brother of Olaf, a zealous defender of the Lutherans, or to allege either in conversation or in his writings that the prelate was a papist. The true Protestants, and foremost among them Zwinglius and Calvin, generally expressed great respect for Luther and for all his disciples, acknowledging them as brethren in the faith. But the sectarian spirit, unfortunately, was beginning now to take the place of the Christian spirit. The influence of the French Protestants, however, made itself felt in other respects and in a wholesome way. Erick, shortly after his accession to the throne, abolished the festival days which were connected with a superstitious system, and the Catholic rites which had been retained in the divine service. He went farther, and made it everywhere known that his kingdom was a free state, open to all persecuted Protestants. Many Protestants, therefore, especially French, came to Stockholm and were kindly received by the king, becoming even particular objects of his favor. This gave rise to jealousies and suspicions. The question was raised whether the king was not a Calvinist in disguise. Wine having become scarce in Sweden, in consequence of the obstacles thrown in the way of the trade by Denmark, it was asked whether it would not be permissible to make use of some other fluid at the Lord’s supper. The Frenchman, Burrey, held the opinion that it would, and this increased the grief of good Lutherans. The archbishop especially declared himself strongly and with good reason against this fantastic proposal, and published a Latin work on the subject.[496] These controversies gave rise to much agitation in Sweden; but they were superseded by troubles of a graver kind. Duke John, Erick’s younger brother, having put forward claims which Erick would not satisfy, and having even caused the king’s envoys to be arrested, and invited the inhabitants of Finland to take an oath of fealty to him and to defend him, was made prisoner on the 12th of August, 1563. [497] A rumor was afterwards current of a conspiracy of the Sture family, who had exercised, before the reign of Gustavus, the royal power as administrators of the kingdom. Their intention, it was said,
  • 67. was to overthrow the house of Vasa and restore the hereditary kingdom to their own family. Erick having met in the street a servant of Svante Sture carrying a gun, this unfortunate man was sentenced to death at the beginning of January, 1567, and several of the Stures and of their friends were thrown into prison. With this incident began the great misfortunes of the prince. Infelicissimus annus Erici regis, he said, speaking of this year in his journal.
  • 68. Madness Of Erick. On May 24 Svante Sture and another of the prisoners had asked pardon of the king and had received a promise of early liberation. In the evening, as the king was walking with Caroli, ordinary (or bishop) of Calmar, some one ran up and told him that his brother, Duke John, had made his escape and had raised the standard of rebellion. In a state of great excitement, he returned to his castle. His mind wandered; he fancied that every one was a conspirator; he saw himself already hurled from the throne; and, beside himself, he went, dagger in hand, into the room in which Nils Sture was confined.[498] He rushed upon the unhappy man and pierced him in the arm; one of his guards gave the fatal stroke. At this moment the prison of the father of Nils Sture opened, and the king, overpowered at the sight, fell at his feet and cried—‘For God’s sake pardon me the wrong that I have done you!’ The old man, who did not know what he meant, answered—‘If any thing should happen to my son, you are responsible to me before God.’ ‘Ah,’ said the king, whose thoughts were wandering more and more, ‘you will never pardon me, and for this reason you must share the same fate.’ He then fled precipitately, as if the castle were full of assassins and every prisoner loaded with chains were pointing a dagger at him. He took the road to Floetsund, attended by some guards; and in a little while one of these returned with an order to put to death all the prisoners in the castle ‘except Sten.’ Two of them bore this name, and considering the uncertainty, both of them escaped, but the rest perished. Ere long the unhappy Erick was seized with horror at the thought of his crime. He believed himself pursued by the ghost of Nils Sture, whom he had slain. Filled with distress and remorse he plunged into the forest. Burrey, who had left the castle at the moment when the order to execute the prisoners arrived, immediately set out in the track of the prince, whom he desired to recall to his senses, and from whom he intended to obtain, if possible, the revocation of the cruel order. He at length came up with him in the middle of the wood; but the raving man fancied that his old teacher had shared in the conspiracy of those whose lives he wished to save. A prey to the most violent madness,
  • 69. he gave an order to one of his guards, and the Frenchman whom he had loved so well, to whom he owed so much, fell at his feet, pierced through and through.[499] The unhappy man then got away from his guards, who were still accompanying him, and fled alone. He threw away his kingly apparel, and wandered about in the woods, in the fields, and in the loneliest places, with a gloomy air, wild eyes, and fierce aspect. No one knew where he was. Like the king of Babylon, he went up and down in the land afar from the haunts of men; his dwelling was with the beasts of the field, and his body was wet with the dew of heaven. At length, on the third day after the murder, he made his appearance in the garb of a peasant in a village of the parish of Odensala; and presently several of his men who were in search of him ran up to him. ‘No, no,’ said he on receiving the acknowledgments of those who respectfully saluted him, ‘I am not king.’[500] ‘It is Nils Sture,’ he added, ‘who is administrator of the kingdom.’ This was the man that he had assassinated. They endeavored in vain to pacify him. ‘Like Nero,’ he exclaimed, ‘I have slain my preceptor.’ He would neither eat nor sleep; all entreaties were fruitless. At last Catherine Maenstochter, to whom he had been strongly attached and who soon became his consort, succeeded in persuading him. He now became more calm and allowed them to take him to Upsala. On June 3 he was taken back to Stockholm. He was in a state of great agitation when he entered the town; his heart rent with remorse, his eyes and his hands raised to heaven. It was a long time before he entirely recovered his reason. Negotiations were set on foot between Duke John and the unhappy king. The former requested an interview with his brother, and this took place on October 9 at Wantholm, or, according to some authorities, at Knappforssen, in Wermeland.[501] The brothers met under an oak tree, which is still called the King’s Oak. They had a second interview shortly after at Swarhjo. Erick, who was perpetually haunted by the thought that the murders which he had ordered had deprived him of the crown, fell at his brother’s feet and hailed him king. From this time he considered himself a dependent on his
  • 70. His Treatment In Prison. brother and spoke sometimes as if he were king and sometimes as if he were a captive. He appeared, at the beginning of 1569, before the States assembled as a high court of justice, and there energetically defended himself, sparing no one, and least of all, the nobility. When John interrupted him by telling him that he was out of his mind, he replied, ‘I have only once been out of my mind, and that was when I released thee from prison.’ He was deprived of the crown on the ground that he had lost his reason, and was sentenced to perpetual confinement, but with royal treatment. Duke John had now reached the summit of his ambition. He set himself to win over adherents, so that no one might be tempted to call to mind the fact that his throne was usurped. He was amiable and obliging alike to the nobles, the ecclesiastics, and the people; and the popularity which he enjoyed seemed daily to increase. ‘Certainly,’ people said, ‘he means loyally to carry out the will of his father.’[502] But the joy and the popularity did not last long. It was soon perceived that he was giving full play to his hatred of Erick, whom he called his most deadly enemy. He spared his life, indeed, at the entreaty of the queen, widow of the late king, but he made him suffer all the horrors of the most rigorous imprisonment. The unhappy prince had to endure in his own body shameful treatment at the hands of his keepers and of those whom he had displeased in the course of his reign. One day a man more mad and more cruel than himself, Olaf Gustavsson, had a violent altercation with him in the prison, and left him lying in his blood. ‘God knows,’ wrote Erick to his brother John (March 1, 1569), ‘what inhuman tortures I am forced to endure— hunger and cold, infection and darkness, blows and wounds. Deliver me from this misery by banishment. The world is surely large enough to allow of the hatred between brothers being mitigated by the distance of places and of countries.’[503] But nothing could appease his enemy, his brother. At first he had allowed him to see his wife and his children, which was a great pleasure to the unhappy man; but this consolation was afterwards refused him. They gave him neither paper nor ink, and in the long hours of his captivity he
  • 71. used to write with water blackened with charcoal on the margins of the books which he was permitted to read. On these he left, in particular, an eloquent defence of his cause. Other motives also came into action to destroy the premature popularity of John III. With the life of Burrey and the prison of Erick the Calvinistic period in Sweden was over; with the accession of the new king the popish period began. Sweden presented at this time an example of the manner in which Rome proceeds to bring back to her feet a people that had departed from her. John took delight in the pomp of the Romish worship, and his wife, a Polish princess, was a decided and zealous Roman Catholic. Although she did not belong to that fanatical, barren, and superstitious ultramontanism which is not even a religion, she firmly believed that outside the pale of her own Church there was no salvation. But her faith was sincere. She had no wish that conversions should be effected by force; nevertheless she was convinced that the best of all good works was to extend as widely as possible the domain of the pope. She had for her confessor a Jesuit, named John Herbest; and the work of darkness, of which this man was one of the principal agents, was carried on in a Jesuitical manner. The king began by listening without objection to the assertions of his courtiers that a moderate Catholicism, a middle stand-point between Popery and Lutheranism, would be the best religion. John thought so. He consequently published in 1571 an ordinance purporting that as Anschar had in the ninth century introduced true Christianity, they must abide by it, and must preach good works, as giving salvation equally with faith. At the same time exorcism at baptism, tapers on the altar, the sign of the cross, the elevation of the host, and the multiplicity of altars were re- established. The archbishop, Lawrence Petersen, offered no opposition to this ordinance, either from weakness of age or of character, from dread of Calvinism, or from fear of the king. His brother Olaf would have been more vigilant and more steadfast. Further steps were soon taken. The queen, at the suggestion of Cardinal Hosius, implored the king to re-establish the dignity of the priest and the sacrifice of the mass.[504] On the death of the
  • 72. Romanism In The Ascendent. archbishop, in 1573, John III. named as his successor Lawrence Gothus, a man who being always willing to yield could not fail to be an excellent instrument for the accomplishment of the purposes of Rome. The king caused to be drawn up seventeen articles, which sanctioned the intercession of the saints, prayers for the dead, the re-establishment of convents and of all the ancient ceremonies. The archbishop signed them; and as soon as this pledge was obtained, the ceremony of the consecration was performed with much pomp. On this occasion reappeared the mitre, the episcopal staff, the great cope called pluvial, and the holy oil for the anointing of the prelate. Henceforth, Catholicism was in the ascendent. John had his son Sigismund brought up in the strictest Romanism, in the hope of thus opening the way for him to the throne of Poland, which Cardinal Hosius had promised him. Two Jesuits, Florentius Feyt and Lawrence Nicolaï, sent by the famous society with which the king was in correspondence, arrived at Stockholm in 1576, and gave themselves out for Lutheran ministers. They ingratiated themselves amiably and adroitly, says one of them, with the Germans, and this at first more easily than with the Swedes.[505] They paid visits to the pastors and conversed with them on all manner of subjects for the purpose of gaining them over. They spoke Latin with ease and elegance, so that the good Swedish pastors, who were unlettered men, were filled with admiration, and promised them their co-operation.[506] Feyt, in a college at Stockholm, newly founded by the king, and Nicolaï, at the university of Upsala, spread out their nets, and by lectures, sermons, disputations, and conversation, they succeeded in bringing back to the abandoned faith now one and now another, thus drawing after them a goodly number of souls.[507] The cardinal lavished his instructions upon them. ‘Let them avoid creating any scandal,’ he wrote to the Jesuit confessor of the queen; ‘let them extol faith to the skies; let them declare that works without faith are profitless; let them preach Christ as the only mediator and His sacrifice on the cross as the only sacrifice that saves.’[508] The main point was to get the Swedes to re-enter the Roman pale by
  • 73. Proceedings Of The Jesuits. giving them to understand that nothing was preached there but the doctrines of the Gospel. This once accomplished, some means would certainly be found of again setting meritorious works by the side of faith, the Virgin Mary by the side of Christ as intercessor, and the sacrifice of the mass by the side of the sacrifice of Calvary. The king commanded all the pastors to attend the lectures of these Jesuits, passing themselves off as Lutherans. These men quoted the writings of the reformers, but at the same time confuted them, and endeavored to show that they contradicted one another. The king was sometimes present at these disputations, and even took part in them. He spoke against the pope, and thus gave the foreign theologians a pretext for making a clever apology for the Roman court. The reverend fathers, moreover, were not particular. They gained over a secretary of the king, named Johan Henrikson, who was living with a woman whose husband he had killed. Father Lawrence, in the first instance, gave absolution to these two wretched people; and afterwards a dispensation to marry. This convert, after having again been an accomplice in crimes, died from drunkenness. In a short time, other Romish priests arrived in Sweden, and were placed in various churches. At the instigation of these missionaries of the pope, many young Swedes were sent abroad, to Rome, to Fulda, and to Olmutz, to be educated there in Jesuit colleges at the expense of the state. Many Roman Catholic books were translated, especially the catechism of the Jesuit Canisius; and these were distributed in large numbers among the people.[509] Cardinal Hosius did not fail to write to the queen that she should by no means be disheartened nor slacken in her efforts to bring about the conversion of the king.[510] At the same time he wrote to the king entreating him to become a true Catholic. ‘If there be any scruple in your majesty’s mind,’ said he, ‘there is nothing upon earth I desire more than with God’s help to remove it.’[511] The queen and her connections at length prevailed upon the king to take one step towards the pope. Count Pontus de la Gardie set out for Rome, with instructions to request the pontiff, on the part of
  • 74. Fratricide. John III., to appoint prayers to be made throughout the world for the re-establishment of the Catholic religion in the North; to propose his own return and that of his people into the Roman Church, upon condition nevertheless that the ecclesiastical estates which were in the hands of the king and of the nobles should remain there, that the king should be acknowledged head of the Swedish Church, that mass should be allowed to be said partly in Swedish, that the cup should be received by the laity, and that marriage should be permitted to the priests, although they ought to be exhorted to celibacy. The court of Rome, without accepting these conditions, left the negotiations open, in hope of getting more another time.[512] The king, desirous of giving the pontiff a mark of his zeal, caused to be composed and printed, in 1576, under the direction of the Jesuits, a new liturgy almost entirely Roman in character; and in the following year he began to persecute those who refused to accept it. Cardinal Hosius now gave thanks to God for the conversion of this prince (October, 1577.) This same prince, who now bowed down his head under the yoke of the pope, signalized this year (1577) by the perpetration of one of those crimes which reveal an unnatural heart, a man devoid of feeling. His unhappy brother, although now rendered completely powerless and reduced to a state of the deepest wretchedness, gave him some uneasiness. Among the people there had been movements in his favor. Mornay had been accused of aiming at the restoration of Erick, and on this charge had been put to death on August 21, 1574. It had been openly said that it would be better for one man alone to suffer than for so many to perish in his cause. In January, 1577, the king wrote to Andersen of Bjurum, commander at Oerbyhus, to which place the ex-king had been recently removed. Here is the order given by a brother for the death of a brother; a document such as is not to be found elsewhere in history. It appears that John recollected his brother’s cleverness and energy, which qualities, however, must surely have been diminished by his imprisonment. ‘In case there should be any danger whatsoever, you are to give King
  • 75. Erick a draught of opium or of mercury strong enough to ensure his death within a few hours. If he should positively refuse to take it, you are to have him bound to his seat and open veins in his hands and feet till he die. If he should resist and render it impossible to bind him, you are to place him by force upon his bed, and then smother him with the mattress or with large cushions.’[513] John III., however, did an act of mercy at the same time. He ordered that, before putting his brother to death, a priest should be sent to the Calvinist Erick, at whose hands he should receive the sacrament. What tender concern for his salvation! The secretary Henrikson, the man who had killed the husband of the woman with whom he lived, consequently arrived at the castle of Oerbyhus accompanied by a chamberlain and the surgeon-major Philip Kern. The latter had prepared the poison, and the three men brought it with them. On Sunday, February 22, the priest presented himself to do his duty. After an interval of two days, the poison was served up to the unfortunate prince in a soup. He took it quite unsuspiciously and died in the night (two o’clock A.M.), February 26, at the age of forty-four.[514] The deposed king had certainly committed a crime when he wounded with a dagger Nils Sture, whose intention he believed was to snatch from him his crown. But at the spectacle of this cold-blooded poisoning, directed in an ordinance with such minute details, and effected in so cowardly a manner, we feel the shudder of horror aroused by great crimes. John then wrote to Duke Charles that their brother had died after a short illness, of which he, the king, had been informed too late. Charles understood what this meant, and he expressed his grief at the unworthy manner in which King Erick had been buried. ‘He was nevertheless,’ wrote Charles, ‘king of Sweden, crowned and anointed; and whatever the evil into which he may have fallen, which may God forgive him! in the course of his reign he did many good deeds worthy of a brave man.’[515] Swedish refugees in various places lamented his tragic end, and even called upon France to avenge it by placing his heir upon the throne.[516]
  • 76. After Erick’s death, the fratricide king continued his progress towards popery. The clever Jesuit, Antoine Possevin, who made his appearance as envoy from the emperor, but who was in fact a legate of the pope, arrived in Sweden, for the purpose of getting the king and the kingdom to decide on making a frank submission to Rome. [517] The king had an interview with him in the convent of Wadstena, and was formally but secretly received by this reverend father into the communion of the Roman Church. While pardoning his sins, the Jesuit imposed on him the penance of fasting every Wednesday, because it was on this day that he had caused his brother to be poisoned.[518] The influence of this Jesuit was at the same time felt throughout the Church. Orders were given to withdraw from the psalms all the passages against the pope, to exclude Luther’s catechism from the schools, and to submit to the canonical laws of Rome, an extract from which was published. Martin Olaï, bishop of Linkoping, having called the pope Antichrist, appeared publicly in the cathedral, and before the altar was stripped of his pontifical decorations. His diocese was given to Caroli, ordinary of Calmar, a former courtling of Erick’s, a treacherous man, who had driven the king to the murder of Sture. At the same time Jesuits were entering the kingdom under various names and various dress; and believing that the time for cautious proceedings was past, they preached vigorously against evangelical doctrine, which they called heretical, so that it began to be said among the common people that these men could do nothing but curse and bark. The district entrusted to the government of Duke Charles was the only one that was protected from this Romish invasion.[519] Suddenly the tide ceased flowing and seemed to turn back towards the fountain-head. John III. had cast his eyes upon the duchies of Bari and Rossano, in the kingdom of Naples, believing that his wife, as the daughter of Bona Sforzei, had some title to them. But the pope had taken a course opposed to his interests; and he had likewise sacrificed Sweden in a treaty, which had been concluded through his mediation, between Russia and Poland. At the same time the principles of freedom which Protestantism had made current,
  • 77. Death Of Queen Catherine. Assembly Of Upsala. especially in opposition to the lordship of the priestly class, had so deeply entered into men’s minds that the practices, the artifices, and the impudence of the Jesuits appeared revolting to the townsmen, and were stirring up in the whole nation a spirit of resistance to the encroachments of the papacy. At length, in 1583, Queen Catherine, who had been the soul of the popish reaction, died; and the king having married again, his second wife, Gunila, declared herself heartily against Rome. At this time the tide, which ever rising had borne along with it into Sweden the rites and the doctrines of Rome, was succeeded by the ebb, which as it retired swept away successively every thing which the rising waters had deposited on these northern shores. The pastor of Stockholm, who had become a Catholic, was deprived; the Jesuits were driven out of the kingdom, and the posts which they held in the college of Stockholm were given to their adversaries. Public opinion energetically declared itself against the adherents of the pope; and the king, turning from one wrong course to another, began to persecute them, although he still retained his liturgy. He died in 1592, and his son Sigismund, a zealous papist, who, since 1587, had been king of Poland, now returning to Sweden, began to oppress Protestantism. His uncle, Duke Charles of Sudermania, an intelligent and enterprising prince, who was not only opposed to popery, but had a leaning towards the Protestant side, put himself at the head of this party. Sigismund was obliged to leave Sweden, and Charles became first administrator of the kingdom and ultimately king.[520] Charles convoked at Upsala a general assembly for the purpose of regulating the state of the Church. On the 25th of February, 1593, he was there present himself with his council, four bishops, more than three hundred pastors, deputies from all parts of the kingdom, many nobles, townsmen, and peasants. There was a young professor of theology from Upsala, Nicolaus Bothniensis, who had distinguished himself by his resistance to Romish institutions, and had even been thrown into prison. The assembly, desirous of doing honor to his
  • 78. fidelity, now named him its president. With one accord the assembly declared that Holy Scripture interpreted by itself was the only basis and the only source of evangelical doctrine. After this all the articles of the Confession of Augsburg were read; and Peter Jona, who had just been named bishop of Strengnaes, rose and said, ‘Let us all hold fast this doctrine; and will you remain faithful to it even if it should please God that you must suffer for so doing?’ All answered, ‘We are prepared to sacrifice for its sake all that we possess in the world, our property and our lives.’ Peter Jona then resuming his speech said, ‘Sweden is now become one man, and we all have one and the same God.’[521] All the changes in doctrine and in ritual which had been introduced in the reign of John III. were abolished. The teaching of evangelical doctrine was universally established. The assembly of Upsala was an event the results of which were felt far and wide, beyond the limits of Sweden. This was manifest when, at a later period, by the services of Gustavus Adolphus, the Reformation was consolidated in Europe.
  • 79. BOOK XIII. HUNGARY, POLAND, BOHEMIA, THE NETHERLANDS.
  • 80. The Magyars. CHAPTER I. THE FIRST REFORMERS AND THE FIRST PERSECUTORS IN HUNGARY. (1518-1526.) Few countries had so much need of the Reformation as Hungary. When, in the year 1000, she abandoned paganism under King Stephen, she attached herself to Rome, and Rome brought on her two evils. She sent into the country large numbers of monks, priests, prelates, primates, and legates; and these men led her—this was the first evil—to a mere outward profession of Christianity, and oppressed the various tribes who peopled the land—this was the second evil. Further, the people, rather more than half a century later, assembled at Alba-Royal, rose in revolt against the clergy. The former were defeated, many were put to death, and the pope, boasting of the victory, wrote to the king, bidding him remember that henceforth the pope of Rome was his suzerain. Shortly before the Reformation, in 1512, the Hungarian passion for independence led them to revolt again. But at this time they were destitute of true Christian principles, and the only result of the movement was to cover their country with devastation, and deluge it with the blood of sixty thousand of its sons. This heroic nation was once more thrown into bondage. The light and the power of the Gospel were needed to effect its regeneration, and to infuse strength into it for resisting its two enemies, the Grand Turk and the pope. If the tribes of Hungary were without a true and living faith, they were nevertheless, the Magyars especially, among the races best fitted to embrace the Reformation. They were characterized by a noble independence of
  • 81. spirit and a nature endowed with higher cravings. When some Christian men proclaimed among them the grace of Jesus Christ, they joyfully embraced the spiritual truths which Geneva was then diffusing in Europe; and the liveliness of their faith, the morality of their conduct, their love of freedom, and the prudence of their character, soon rendered a glorious testimony to the Reformation. But the cleverness and the violent persecuting spirit of the Hungarian prelates and of the courts of Rome and Vienna contended vigorously against the religious renovation of this people, drew them back in part to the bosom of the Church, and prevented the spread of evangelical doctrine into other districts of the country. The mighty forces of the flesh engaged in a conflict with the mighty forces of the spirit. The dominion of prejudice gained the ascendency over that of truth. Faith, wisdom, virtue, originative energy, freedom—all were crushed. God, however, by his power, kept for himself a people in these lands; and a considerable part of the Hungarian nation remained Protestant, but were constantly subject to the inspection of priests and to oppression by the powerful. Hungary, in common with the other countries of eastern Europe, had received, before the Reformation of the sixteenth century and while it was still in subjection to Rome, some rays of light which here and there illumined it. Some of the Vaudois had sought refuge there; the doctrine of John Hus had been spread in the land; some of the brethren banished from Bohemia had built churches there, and had acquired great influence. In 1521 two young people, children almost, the hope of Hungary, were united before the altar. The husband was Louis II., a son of King Ladislaus, who had ascended the throne in 1510, at the age of ten. The young prince, who was amiable, but easy tempered, weak, and addicted to pleasure, was not capable of preventing the prevalence of disorder in the kingdom at the time the Turks were threatening it with their terrible invasions. He had little courage, a quality which was common enough among his fellow-countrymen; he was obstinate, and yet allowed his courtiers and his bishops to rule over him:
  • 82. Beginning Of Reformation. Et les prêtres en paix guidaient ses faibles ans. The wife, named Mary, aged eighteen years, was of quite a different character. A sister of Charles the Fifth, a daughter of the unfortunate Joanna, queen of Castile and Aragon, who was kept in prison till her death, partly perhaps because she preferred the Gospel to the pope, Mary like her mother and still more than her mother had tasted the doctrine of the Gospel. Of lofty character, with a kindly heart, a sound understanding, and high intellectual abilities, well informed and able to speak five languages, it was said of her that she was as competent to rule over minds in peace as to command armies in war. She did not actually march at their head, but she once caused a severe defeat to be given to Henry II., the son of Francis I. While still very young and residing at the court of her grandfather Maximilian, she had read with delight the first works of Luther. ‘Her chamber was her oratory,’ said Erasmus. She loved the chase, but she did not start for this sport without taking with her her New Testament. She was equally fond of pursuing on horseback the hart and the hare, and of sitting under a tree to read the word of the Saviour. We have elsewhere mentioned the fact that while she was at Augsburg in 1530, in company with her brother Charles the Fifth and the archbishops, bishops, and legates of the papacy, she courageously had the evangelical services celebrated in her apartments. Melanchthon called her a woman of heroic genius. She would fain have given her protection to the Reformation in Hungary, but the influence of the priests over the king was stronger than her own. Subsequently also she entreated the emperor not to submit to the domination of the clergy.[522] It was by a kind of thunder-clap that the Reformation began in Hungary. In 1518 there appeared a work entitled, De Horrendo Idololatriæ Crimine. In 1520 and 1521 the earliest writings of Luther, on Christian Liberty, on the Epistle to the Galatians, and others besides, were brought into the kingdom by traders who came from Germany. The Captivity of Babylon delighted the Hungarians, and led many of them to
  • 83. separate themselves from the ultramontane Roman Church. Other evangelical books explaining the doctrine of salvation were read with eagerness. Nobles and townsmen declared for the Reformation; and this they did with all the energy of their national character. The like events were taking place in Transylvania. Progress so rapid could not but provoke persecution. It was to begin with anathemas, but it would soon go on to rigorous deeds, and would rage almost without intermission. Szakmary, archbishop of Gran, hoping to annihilate Reform at one blow, assembled his scribes, and had a public document drawn up. In 1521 condemnation of Luther and of his writings resounded from the pulpits of the principal Hungarian churches.[523] Most of the Hungarians who heard this were very much astonished; and the publication of the anathemas produced a contrary effect to that which the prelate had aimed at. It awakened in the hearers a consciousness of the important nature of the Reformation; so that its friends were encouraged, and many were led to seek after the truth who had not previously concerned themselves about it. Many ecclesiastics, especially, who had been oppressed by the higher clergy, and had long sighed for the time of justice and freedom, now lifted up their heads, read the sacred books, and declared that Luther’s doctrine, founded on the Word of God, alone was true. They did not remain inactive; but by their living and powerful words they enlightened the minds of men. Parishes, villages, and towns joyfully greeted the Reformation. One of the first to proclaim the Gospel in Hungary appears to have been Thomas Preussner. Others followed him. Cordatus at Bartfeld, in 1522, Siklosy at Neustadt, Kopacsy at Sarospatak, Radan and Husser at Debreczin, and George at Hermanstadt, proclaimed the tidings of a salvation freely given to those who laid hold on Christ by faith. Learned men at the same time were bearing witness to the truth at the university of Buda. Simon Grynaeus, son of a simple Suabian peasant, and afterwards a friend of Calvin, having from childhood shown a remarkable disposition for study, had been sent
  • 84. Hungarians At Wittenberg. at the age of fourteen to the famous school of Pforzheim. Thence he had passed to the university of Vienna, where he distinguished himself and took the degree of master of arts. The king then called him to Buda. Grynaeus did not confine himself to teaching letters there, but openly and boldly announced to the people the great doctrines of the Gospel which he had embraced with all his heart. Another doctor, Winsheim, also professed openly the same faith; and, what was an unlooked-for event, people were talking at Pesth, in the old capital of the kings, on the banks of the Danube, and near the borders of Turkey, of that same Word of God which was giving joy to so many Germans on the banks of the Elbe. The Reformation, like a broad river, brought life and prosperity into these vast regions which extend between the Alps, the Carpathian Mountains, and the Balkan. But, alas! the river, dried up here and there by the parching heat of persecution, was one day to shrink and be turned into a stagnant and sleepy body of water like that which runs to lose itself in the dry sands of the desert.[524] These times, however, were as yet remote. The reformation of the Magyars was still in its period of growth and life. The tidings of the struggle which had begun in Germany excited in men’s minds a burning desire to see Luther, to hear him, and to receive from his very lips the heavenly doctrine.[525] This is a characteristic feature of the Hungarian Reformation. The wish to go and drink the living water at its very source became intense, and all who were able to do so hastened to Wittenberg. Martin Cyriaci from Leutschau arrived there in 1522. He was followed in 1524 by Dionysius Link, Balthazar Gleba from Buda, and a great number of their countrymen.[526] Joyfully they greeted the modest city from which light was shed over the world. They fixed their gaze with timid respect on Luther and on Melanchthon; took their places on the benches of their auditories; received into their minds and hearts the words of these illustrious masters, and engraved them there more indelibly than on the leaves of their note- books.
  • 85. Intolerance Of The Priesthood. In Hungary it began gradually to be noticed that one student and another was missing. The cause of their absence became known; they were gone to Wittenberg. The bishops, provoked at these heretical pilgrimages, denounced them to the king. These priests had no difficulty in getting their views adopted by this young man, who, but a little while before, had given proof of his character. Louis, who was king of Bohemia as well as of Hungary, had gone to Prague for the coronation of the queen, Mary; and as he passed through Moravia he had a parley with the townsmen of Iglau, and had declared to them that unless they abandoned the Saxon heresy he would have them put to death. At the same time he had ordered their pastor, John Speratus, to be thrown into prison. This was the wedding bouquet which Louis II. presented to his young, lovely, and Christian spouse, on the occasion of her coronation.[527] The archbishops and the priests, in possession of all their privileges, put themselves at the head of the opposition. Many of them, of course, were actuated by a higher motive, the glory of the Roman Church; but in general they had no mind to let what they had usurped be taken from them. King Louis and other princes, pressed by the clergy, lent them their own power and authority; but the ecclesiastics were the authors of the persecution. A religious philosopher of the eighteenth century[528] has said, ‘The clergy are the indirect cause of the crimes of kings. While they talk incessantly of God, they only aim at establishing their own dominion.’ This is a strong saying, and the author forgets that in the Catholic Church there are, and always have been, some good priests and good laymen. Let us not exaggerate. Still, the empire of the clergy, the despotism with which it crushed consciences, is a great historical fact. It concealed the Holy Scriptures, but it brought out its tariffs of indulgences, its exactions, its punishments with fire and sword. At a later time the progress of Christian civilization no longer allowed resort to such barbarous practices. But if evangelical Christianity is exposed henceforth only to senseless accusations, and frequently to insults on the part of the adherents of Rome, another adversary has
  • 86. Welcome to Our Bookstore - The Ultimate Destination for Book Lovers Are you passionate about books and eager to explore new worlds of knowledge? At our website, we offer a vast collection of books that cater to every interest and age group. From classic literature to specialized publications, self-help books, and children’s stories, we have it all! Each book is a gateway to new adventures, helping you expand your knowledge and nourish your soul Experience Convenient and Enjoyable Book Shopping Our website is more than just an online bookstore—it’s a bridge connecting readers to the timeless values of culture and wisdom. With a sleek and user-friendly interface and a smart search system, you can find your favorite books quickly and easily. Enjoy special promotions, fast home delivery, and a seamless shopping experience that saves you time and enhances your love for reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookgate.com