Archive for the ‘ MVC’ Category

In the previous post in this Contoso Karate MVC Series we re-factored our LogIn control widget into a PartialView. We did this for a few reasons.

  • Views want to be associated with only one model and we want to reserve that model for one that is more central to the particular page being displayed. (Specifying the Model for the view in the page _Template is generally a bad idea since that model will then be THE model assumed for every page that derives from that template. Partial views are one of the ways that we can solve this problem, a ViewModel is another.)
  • Partial views are very easily reusable.
  • If other considerations don’t preempt their use, Partial Views can make your actual View Markup easier to understand.

In this post I’ll build another Partial View. Please read the previous post to understand why we need partial views in the context of our fairly complex user interface design.

So, lets suppose that we have a requirement for an alert / notice box on our home page. It could contain special data, like for example a notice that classes are canceled due to bad weather.

It might look like this.

In this case our UI Widget is slightly more complex because we will need to retrieve data from a database to display from inside our partial view. We will store all the site notices in the database so that we have a historical record but we’ll only display the most recent one.

So, we’ll need a data table to store our notices. I like to keep the ASP.NET Services data (membership, etc) separate from my domain specific data so I created a new database named CKCMS for Contoso Karate Content Management System.

You probably know the drill. Right-Click in the solution, select Add -> New Item, choose the data items collection and select New SQL Server Database.

In Visual Studio, Switch from the Solution Explorer to the Database Explorer.

Expand the view on the database that was just created and right-click on the tables folder.

Add the fields as shown in the following table view.

When you save the table, name it “Notices”.

Note that the IsLive column will not be used in this demo. I’ve added it for future use. (We may want to be able to display more than one notice at a time in a future version of the application.)

Since we’ll need to access the data, I created an ADO.NET Entity Model.

Right-Click on the Models folder and choose add new item.

Select “Data” to see the data items collection and choose ADO.NET Entity Data Model and specify the name “CKSMSDBModel”  (Contoso Karate Content Management System Database Model.)
Read the rest of this entry »

Refactoring the Contoso Karate MVC LogOn Widget.

Just recently I published this post about creating a “logon widget” for the ASP.NET MVC Contoso Karate application that I’ve started building.

In this post I’m going to re-factor it.

Why, you ask? Well, sometimes it’s easiest to demonstrate techniques in a “simple” way  that is not necessary the most practical way.

Such is the case of our “login widget”.

ASP.NET MVC imposes a LOT of conventions. We could have technoligious discussions ad nauseam about why the MVC way is the best way (or not). I have FAR to many of these conversations but lets just agree that for some developer’s preferences and in certain types of application needs, the impositions of the pattern pay long-term dividends.

The idea of MVC (Model – View – Controller) lets us achieve “Separation of Concerns”. While this is not necessary (I know – sacrilege!) it is normally a beneficial thing. 

But, whenever a pattern or an implementation is meant to support a specific way of doing things it can get in the way.

The problem in this case is that a view (by default) sort of wants to be rendered using a SINGLE model.

take for example the following web site layout from a Joomla theme by RocketTheme

This is a pretty common kind of web user interface and one that will be very difficult to serve using a single data source.

You’ll recall from the previous post that we want the LogOn widget to appear on every page  but we accessed the model for the login data by referencing the LogOnModel that is innate to ASP.NET MVC applications that are created using the default ASP.NET MVC template.

It works fine, but our pages will stop working as soon as we try to reference an additional model in our views as views want a SINGLE model to work with.

No problem. Not only is there a way to do what we want (now that we understand the code that delivers the LogOn behavior that wer want) there is a much better, reusable way.

Enter “Partial Views”

Note that I’m not posting screen shots here because the User Interface will look and work EXACTLY like that you will find in the previous post referenced above.

To create a Partial View you will right-click on the folder where you want that Partial View to be created. Since we want our “LogIn Widget” to be able to be used anywhere, we’ll Right-Click on the \Views\Shared folder, choose “Add and then “View”.

Note the sections indicated in the image above.

I chose a name that begins with an underscore (I don’t want this partial view to ever be rendered directly) and ends with the word “partial” so that I can tell at a glance which of my views are “full” views and which are partial.

In addition I select the check box that instructs the wizard to create a partial view.

Once I complete the wizard my

Views\Shared folder will contain a file named _LoginBoxPartial.cshtml

Next, I need to move two bits of code from my site’s _Layout.cshtml page.

  • The MOdel declaration at the very top.
  • The conditional markup that we put in the _Layout file to create the LogIn or LogOut box, depending on the user’s state of authentication.

 The complete code of our partial view (_LoginBoxPartial.cshtml) loosk like this:



@model ContosoKarateMVC.Models.LogOnModel
@if (!User.Identity.IsAuthenticated)
{
    using (Html.BeginForm('LogOn', 'Account', FormMethod.Post))
    {
        <div class='editor-label'>
            @Html.LabelFor(m => m.UserName)
        </div>
        <div class='editor-field'>
            @Html.TextBoxFor(m => m.UserName)
            @Html.ValidationMessageFor(m => m.UserName)
        </div>
        <div class='editor-label'>
            @Html.LabelFor(m => m.Password)
        </div>
        <div class='editor-field'>
            @Html.PasswordFor(m => m.Password)
            @Html.ValidationMessageFor(m => m.Password)
        </div>
        <div class='editor-label'>
            @Html.CheckBoxFor(m => m.RememberMe)
            @Html.LabelFor(m => m.RememberMe)
        </div>
        <span class='style-button-wrapper'>
            <span class='style-button-l'> </span>
            <span class='style-button-r'> </span>
            <input type='submit' name='Submit' class='style-button'
			       value='Login' />
        </span>
        <hr />
        <ul>
            <li>
		@Html.ActionLink('Create an Account.', 'Register', 'Account')
	    </li>
        </ul>
    }
}
else
{
    using (Html.BeginForm('LogOff', 'Account', FormMethod.Post))
    {
        <span class='style-button-wrapper'>
            <span class='style-button-l'> </span>
            <span class='style-button-r'> </span>
            <input type='submit' name='Submit' class='style-button'
			                     value='Logoff' />
        </span>
    }
}

Then we just need to insert a call to render our partial view in the same location as when the markup was in-line in the Layout file.


@{ Html.RenderPartial('_LoginBoxPartial'); }

Now the Views that derive from our _Layout.cshtml page are free to use whatever model they desire and our LogIn feature will still work.

What’s more, we can reuse the Partial View anywhere in our project.

Note: I’m intentionally not posting a like to the source code (you can easily change the source from the prior post.)

In my NEXT post I’ll illustrate a more complex use of “Widgetry” and I will post the code at that time.


Adding a site wide Log In Features to an ASP.NET MVC Web Site.

Having fitted the theme generated for the Contoso Karate Web Sites (see the previous posts in this series) it’s time to start adding functionality to the template.

If you’re new to ASP.NET MVC, let me take this opportunity to encourage you to stick with it. Much is different and sometimes this makes things especially frustrating because not only do we have to learn new things, but the new things work quite differently than we expect based on our previous experience.

Be tenacious, it’s worth it.

Here is our first feature scenario. My Contoso Karate site will have a “portal” feel to it. The default ASP.NET MVC Internet Application template has a separate page for the user to use to authenticate (Log In) but I want the user to be able to log in from any page in my website.

It’s very common for web sites to have a “Log In” widget in the side bar of their theme, like this:

I want the user to be able to Log In by entering their User Name and Password right here on the Home page, or any page in the site that uses the default page template.

To do this in a functionally complete way I need to provide for several behavioral considerations.

  • The user does not yet have an account on the site and needs to create one.
  • The user submits the form without entering the required User Name and Password.
  • The user fills out the form but the user name and password to not match any in the authentication database.
  • The user entered a valid user name and password and is authenticated when the user clicks the submit button.

In the last case, it doesn’t make sense to continue to show a Log-In feature after the user successfully logs in so we should conditionally display a Log-Out option is the current user is authenticated.

ASP.NET WebForms developers have traditionally been bound by the restriction of a single HTML form to each .ASPX page. (Though technically there are ways around this issue and the server-side execution model for user interface element events made this more or less irrelevant.)

While ASP.NET WebForms abstracts the “nature” of World Wide Web applications, ASP.NET MVC embraces it.

An ASP.NET MVC View can contain any number of html forms and each form’s action attribute can submit to any controller and action (and http method) that we need.

So to create the Log-In feature in the right column of our template (_Layout.cshtml) we will insert an html form object. We will do this using the @Html helper object.


using (Html.BeginForm('LogOn', 'Account', FormMethod.Post))
{
   <div class='editor-label'>
      @Html.LabelFor(m => m.UserName)
   </div>
   <div class='editor-field'>
      @Html.TextBoxFor(m => m.UserName)
      @Html.ValidationMessageFor(m => m.UserName)
   </div>
   <div class='editor-label'>
      @Html.LabelFor(m => m.Password)
   </div>
   <div class='editor-field'>
      @Html.PasswordFor(m => m.Password)
      @Html.ValidationMessageFor(m => m.Password)
   </div>
   <div class='editor-label'>
      @Html.CheckBoxFor(m => m.RememberMe)
      @Html.LabelFor(m => m.RememberMe)
   </div>
   <span class='style-button-wrapper'>
      <span class='style-button-l'> </span>
      <span class='style-button-r'> </span>
      <input type='submit' name='Submit' class='style-button'
         value='Login' />
   </span>
   <hr />
   <ul>
      <li>
    @Html.ActionLink('Create an Account.', 'Register', 'Account')
      </li>
   </ul>
}

Notice that the form labels and fields are referencing a data model (m.UserName). The model is the LogonModel that we get by virtue of starting our project from the default ASP.NET MVC Internet template.
Read the rest of this entry »

Contoso Karate MVC – Migrating the Theme from WebMatrix

I’ve been a bit slow doing getting all the Contoso Karate Sites that I want to build off the ground.

A couple of weeks ago I started posting about Contoso Karate WebMatrtix [ read HERE ]

To get started with the MVC version, the first thing that I needed to do was to get the theme implemented.

So, I created an ASP.NET MVC site using the default ASP.NET MVC template.

Then I took the markup from the _SiteLayout.cshtml page from my Contoso Karate Web Matrix site and copied it to the _Lyout.cshtlm page

When I first ran (F5) the site in Visual Studio – I get a pleasant surprise :

There was only one change that I needed to make.

Since there is no 1-to-1 relationship between physical endpoints and urls, the can “view” can be requested using different URLs

ie: http://localhost/ & http://localhost/home will result in the same view being rendered.

So I changed resource references (images, etc) in my view to use the magic “HRef” helper.

- @Href(“~/Content/Images”)

You can learn more about the ASP.NET Razor Syntax [ HERE ]

You  can download the Runnable Contoso Karate MVC Theme [ HERE ]

ASP.NET MVC App Building Videos (61)

Building the ASP.NET MVC Music Store


Part 1: Intro, Tools, and Project Structure
Part 2: Controllers
Part 3: Views and ViewModels


ASP.NET MVC 2


Displaying a Table of Database Data
Creating Model Classes with LINQ to SQL
Creating Unit Tests for ASP.NET MVC Applications
Preventing JavaScript Injection Attacks
An Introduction to URL Routing
Understanding Views, View Data, and HTML Helpers
Understanding Controllers, Controller Actions, and Action Results
Understanding Models, Views, and Controllers
Creating a Tasklist Application with ASP.NET MVC
Understanding Models, Views, and Controllers
ASP.NET MVC Controller Overview
Creating a Movie Database Application in 15 minutes with ASP.NET MVC
How Do I: Return JSON Formatted Data for an AJAX Call in an ASP.NET MVC Web Application?
What is ASP.NET MVC? 80 minute technical video for developers, building NerdDinner
Why ASP.NET MVC? 3 minute overview video for decision makers
ASP.NET MVC: How? 10 minute technical video for developers
How Do I: Work with Data in ASP.NET MVC Partial Views?
How Do I: Create a Custom HTML Helper for an MVC Application?
How Do I: Work with Model Binders in an MVC Application?
How Do I: Use HttpVerbs Attributes in an MVC Application?
MVC 2 HTML Encoding
MVC 2 Strongly Typed Helpers
MVC 2 Model Validation
MVC 2 Template Customization
ASP.NET MVC 2 – Areas
ASP.NET MVC 2 – Render Action


ASP.NET MVC Talks


Creating NerdDinner.com
America’s Next Top MVC Framework
Ninja on Fire Black Belt Tips
ASP.NET MVC 2: Ninja Black Belt Tips


ASP.NET MVC For the Rest of Us

(Building a Contact Form App)


#1: ASP.NET MVC For the Rest of Us: Part 1
#2: ASP.NET MVC For the Rest of Us: Part 2
#3: ASP.NET MVC For the Rest of Us: Part 3
#4: ASP.NET MVC For the Rest of Us: Part 4


ASP.NET MVC Storefront Starter Kit


#1: Architectural Discussion and Overview
#2: The Repository Pattern
#3: Pipes and Filters
#4: Linq To Sql Spike
#5: Globalization
#6: Finishing The Repository, and Initial UI Work
#7: Routing and UI Work
#8: Testing Controllers
#9: The Shopping Cart
#10: Shopping Cart Refactor and Authorization
#11: Hooking Up the Shopping Cart & Using Components
#12: Mocking
#13: Dependency Injection
#14: Rich Client Interaction
#15: Public Code review
#16: Membership Redo With OpenID
#17: Checkout With Jeff Atwood
#18: Creating An Experience
#19: Processing Orders With Windows Workflow
#19a: Windows Workflow Followup
#20: Logging
#21: Order Manager and Personalization
#22: Restructuring, Rerouting, and PayPal
#23: Getting Started With Domain-Driven Design
#24: Finis


Free ASP.NET MVC Training Online

The MVFConf sessions are now on-line and available for viewing or download !

del.icio.us Tags: ,,,,

ASP.NET MVC Fundamentals Videos & Tutoruals (39)

MVC Step by Step Tutorials


Build your First ASP.NET MVC 3 Application
Build an ASP.NET MVC Music Store


MVC Sample Saamplications

NerdDinner
ASP.NET MVC Music Store
Microsoft TownHall


ASP.NET MVC Overview


ASP.NET MVC Overview
Understanding Models, Views and Controllers
Understanding the ASP.NET MVC Execution Process
Create Movie DB App
ASP.NET MVC 2 Basics
Create a MVC 3 Application with Razor & Unobtrusive JavaScript


ASP.NET MVC Fundamentals Videos


Creating a Movie Database Application
Preventing JavaScript Injection Attacks
Creating Unit Tests
Creating Custom HTML Helpers
Return JSON Formatted Data for an AJAX Call
ASP.NET MVC Controller Overview
Understanding Models, Views, and Controllers
Understanding Views, View Data, & HTML Helpers
An Introduction to URL Routing


ASP.NET MVC For the Rest of Us Videos


ASP.NET MVC For the Rest of Us: Part 1
ASP.NET MVC For the Rest of Us: Part 2
ASP.NET MVC For the Rest of Us: Part 3
ASP.NET MVC For the Rest of Us: Part 4


ASP.NET MVC Routing


ASP.NET Routing Overview
Creating Custom Routes
Creating a Route Constraint
Creating a Custom Route Contstraint


ASP.NET MVC Controlers


ASP.NET MVC Controller Overview
Creating a Controller
Creating an Action


ASP.NET MVC Views


MVC Views Overview
Creating Custom HTML Helpers
Displaying a Table of DB Data
Using the Tagbuilder Class


ASP.NET MVC Testing


Creating Unit Tests


ASP.NET MVC Navigation


Providing Website Navigation with Sitemaps


ASP.NET MVC Performance


Improving Performance with Output Caching
Adding Dynamic Content to a Cached Page


Orchard 1.0 – We’re ready for production !

OrchardLogoCodeplex

If you’re like me you’ve been waiting with anticipation for this Orchard 1.0  !

Well, we’re LIVE.

The primary differences between 0.8 and 1.0 is bug fixes but the milestone is that we’re production ready so we can starting building sites, modules, and themes with confidence.

Get the RTW version [ HERE ]

… and if you build a Module of Theme, make sure you let me know so I can blog about it !!

Choosing between ASP.NET–WebForms, MVC, WebMatrix – Choice is a GOOD thing.

Yesterday Microsoft announced new (beta) releases of  a number of forthcoming web development technologies. [ Read HERE ]

A member of one of the mailing lists I’m on was very upset! He complained that TWO choices were two many (WebForms and MVC) and adding a THIRD (WebMatrix) was simply ridiculous.  I know he was serious because he said “seriously” many times.

ScottGu posted an interesting opinion [ About Technical Debates (and ASP.NET Web Forms and ASP.NET MVC debates in particular)  ] on his blog some time ago.

Now that I’m MSJoe and not the MisfitGeek, I’m trying to be more political correct (as demanded by management : ) ), and I don’t mean to call out that specific individual, but the email thread got me to thinking.

If you read the developer blogosphere, there are many thousands of developers out there that are sure they could do a better job guiding Microsoft Developer Platform Strategy than our current leadership, they just choose not to come be part of the solution, but in this instance someone was saying that “choice options” are a bad thing.

Now, no one was saying that THE choice (WebMatrix) was bad, only that having three different options to choose from was bad.

I think people complain about having choices comes from one of three things.

1.) I don’t want to have to MAKE choices, either because I don’t want to (or have the time) to learn about the choices so that I can make the right choice for my needs.

2.) Confidence issues. I don’t want to have to make a choice because I might not make the right one (or be able to defend it.)  If there is only ONE choice then I can’t get blamed for it

3.) I already MADE my choice so no other choices should be needed by anyone, any where ever !

BAD choices can be bad, but have several good choices is just…. well, good.

So, I’ll talk about the three choices (and really there are more than three.)

1.)  ASP.NET WebForms

It’s become fashionable in some circles to say “WebForms sucks”.

Look back a decade to when ASP.NET WebForms first hit the street and reflect on how WebForms was pure genius back then.

People were building “Client / Server” applications with Visual Basic, Borland Delphi, PowerBuilder, etc. and suddenly everyone needed to move business applications to the World Wide Web. ASP.NET WebForms gave developers a way to do that using the exact development paradigm that they had already been using for years in the Client Server world without having to learn much f anything about how the Internet or the World Wide Web actually worked.

It was a brilliant solution to the problem of the day – get developers productively building applications for the web with as little time lag and learning curve as possible !

ASP.NWET WebForms FTW !!!!

Only many years later has the technical abstraction provided by ASP.NET WebForms become a hindrance. (And really, only a hindrance to some developers.)

So if you are a web developer building applications with ASP.NET WebForms should you move to something else ?

Not necessarily.

There are LOTS of GREAT web applications built with ASP.NET WebForms. If it works for you – keep doing it.

Also, there are many different STYLES of development possible with ASP.NET WebForms.

If certain parts of the WebForms layer get in the way, you can probably turn it off, or not use it.

Don’t like ViewState, turn it off (at whatever level of granularity you like).

Don’t like the WebForms Controls, don’t use them (replace them with jQuery UI ! )

1950-PanHead

This 1950 Harley Davidson Pan Head has modern paint and an after market seat but is still an awesome choice !

I still write new applications in ASP.NET WebForms.

2.) ASP.NET MVC

Proponents say MVC is the “Modern” way.

MVC is a “Pattern” that has been in use for more than THIRTY years. ASP.NET MVC is an implementation of that pattern for building .NET Web Applications.

There are good reasons to choose ASP.NET MVC for your new Web Application Development.

  1. Pattern supported separation of concerns. (Though undesirable development practices can break this model.)
  2. Embrace (rather than abstract) the underlying nature of the World Wide Web.
  3. Strong facilities for Unit Testing.
  4. Well suited to “Agile” development practices.

Certainly one can do all those things with ASP.NET WebForms, but ASP.NET MVC was designed and built with these things in mind.

There is a rather steep learning curve to start working with ASP.NET MVC. The implementation relies heavily on development by “convention” which means you need to spend time figuring out where certain things HAVE TO go or what the names of CERTAIN things MUST be.

And, there are choices to be made such as with View Engine to use (Forms, Razor, etc.)

When it comes to UI you’re sort of on your own (which some of us really like) though there is tooling support built in for jQuery coding.

The most important reason for one to choose ASP.NET MVC is simple.

Because it most facilitates they way you WANT to build web software !

If I were building a new application that was going to be built and maintained by a single company I would probably  choose ASP.NET MVC.

3.) ASP.NET WebMatrix

Ahhh, now for the “New Kid on the Block”. 

This is the one the uber-geeks say we don’t need.

I say they’re WRONG.

ASP.NET WebMatrix is not an APPLICATION Centric development methodology (like ASP.NET MVC), it is a PAGE CENTRIC development model.

The first important thing to note in this regard is that MANY Web Developers simply PREFER this model for developing Web Applications.

MANY web applications are built this way without the mandatory implication of a specific pattern, without Unit Testing, without Agile methodologies, etc.

In fact, most of the MOST popular web applications have been built this way.

Classic ASP developers work this way. So do PHP developers.

WebMatrix is perfect for Web SITES – and much of what we use on the web are more “sites” than applications”.

The web “page” model also has a special place in community driven Open Source development.

Projects like WordPress have grown HUGELY successful due to wide spread community involvement. The page centric development model really resonates well because the learning curve for contribution is low enough to offer rapid satisfaction. One doesn’t need to “get” the architecture, etc to start building and sharing things of interest to them.

And, like all the technologies I’ve been talking about here you are free to use the JavaScript strategy of your choice, AJAX, Silverlight, Flash, etc. – whatever you desire. 

So, which to choose ?

Yea, I know we tend to like it when there is a clear winner, or at least when someone declares a clear winner, even if you disagree.

The problem is that there are “hard” criteria but in the end, preference wins.

Some people drive a sports car, others drive trucks. (I bought an SUV with a big v8 engine so I get utility and whiplash whan I stomp on the pedal.)

I can’t TELL YOU when YOU should choose, but I can tell you how I choose.

 

I choose WebForms When ……

I don’t have the issues with WebForms that some folks seem to have developed. I don’t find it that difficult to get under the covers and I don’t mind writing custom controls if I need to. Still, more and more I find that WebForms makes sense to me when I’m building “behind the firewall” applications.

  • An app who’s UI can mostly be limited to the ASP.NET WebForms controls.
  • An application that will be GRID Centric.
  • An app that is mostly Data and the Screens that show / edit them. (Little “business logic” need be added.
  • Rapid Prototypes or Use & retire applications.

 

I choose ASP.NET MVC When …..

  • The app wants to be a “Web 2.0” type thing.
  • The UI will need to be complex and or very interactive.
  • The application will have a great deal of business logic and / or is mission critical.
  • The app needs to have an extended functional lifespan and will experience evolutionary iterations.

I choose WebMatrix when …..

  • The “app” is “Site Centric”.
  • UI is king but data and business logic are minimal.
  • I want the application to be Open Source AND I want it to take on a life of its own.

Still, I continue to work with all three.

BOOK – Sample Chapter ASP.NET MVC 1.0

I’ve avoided ASP.NET MVC for a long time. Don’t get me wrong, it’s cool. I just haven’t needed it. WebForms suits, and continues to serve me quite well.But still, as a developer who also does a lot of PHP (and other) web development. Sometimes I wanna use the “do it yourself” web dev model. Enter ASP.NET MVC

Some of our guys wrote this book and it’s now shipping from Amazon.com

You can grab a free sample chapter HERE

Technorati Tags: ,,

ASP.NET MVC Design Gallery and Design Competition

For some time now we’ve been working on a new option for ASP.NET Developers. ASP.NET MVC !

Phil Haak and the crew have been furiously at work on ASP.NET MVC and Stephen Walter (with great work from Phil, Tom, Jay, Jay-E, Rich, Zac, and JM) has been building a gallery to show off great MVC designs.

It’s NOW LIVE HERE (http://www.asp.net/MVC/Gallery/)

To kick things off WE’RE HAVING A CONTEST !!!

You can get all the details and submit your design until January 31st HERE (http://www.asp.net/MVC/Gallery/Competition/)

Cool Flickr app in MVC using custom LINQ

Mehfuz Hossain, a Microsoft MVP & Developer at Telerik has created a cool flickr with asp.net MVC that you might like to check out.

The url is : www.flickrmvc.net  and the source code can be found at www.codeplex.com/flickrXplorer.

It is built on the Athena (A LINQ to flickr API) -  one of the early LINQ providers (also written by Mehfuz) which you can get at www.codeplex.com/linqflickr.

Also, LINQ to flickr is built on LinqExtender,  a toolkit that helps you make your own home grown LINQ providers without knowing much of anything about LINQ. You can find that project here – www.codeplex.com/linqextender

Have Fun!!!