Category Archives: MVC

Render a View or Template Using JavaScript

This post builds off my previous one ASP.NET MVC Model Binding to a List.  This post is about how to render a partial view when you make an AJAX call.  This will also work with an EditorTemplate or a DisplayTemplate.  I personally recommend using a partial view as you can take advantage of model binding for your templates better, as you will see, doing this from an AJAX call is a little different.

Read the rest of this entry

ASP.NET MVC Model Binding to a List

Microsoft’s implementation of MVC is very nice; especially the Model Binding feature.  What happens if you have a List<T> of objects that are part of your model?  Can you still use the awesomeness that is Model Binding?

Read the rest of this entry

Custom Error Handling In MVC 5

Creating a custom error page in MVC 5 is not too difficult.  If you want to have one that is server farm friendly, well that is not too tough either.  I created a little demo project for doing custom errors that passes a model around.  To be effective in handling uncaught errors we will need to use the Global.asax Application_Error method.  You can also use this method to send errors that you catch but just cannot handle or fail out of gracefully.

There are a number of reasons why you may want to do custom errors like I do below.

  • You are in a server farm or other environment where Session based objects will not work
  • Display a user friendly message based on the error received
  • Display a user friendly message based on an HTTP Code (if one was returned)
  • Log the error
  • Send a notification of the error

Read the rest of this entry

MVC 5 Placeholders, Prompts and Watermarks

I have noticed an issue with the MVC project in Visual Studio that I am sure others have seen too.  I say this because I have seen a number of solutions in StackOverflow and the ASP.Net forums.  This post is not about some great way to write your own extensions and automagically have the placeholder set in the HTML that is displayed to the user.  No, this is a much simpler method.

Just manually set the placeholder in your Razor syntax.  Chances are you are going in there anyway to tweak a few things instead of using what Visual Studio scaffolded for you.  I would still recommend setting the Prompt in your model though, I suspect that one day this will get fixed or you might actually need it to be automatically generated.  In fact I’d say that if you are writing your own Edit Templates you should include the small extra step to make it auto-generated.

If you are not doing that, here is the easiest fix or work around.

Read the rest of this entry

A Good MVC Database First Tutorial

I know there are a lot of examples out there of MVC Code first, but there does not seem to be a whole bunch on Database first.  I did find a really nice one, even though it is a bit old.

Julie Lerman had created a post about Building an MVC3 with Database First and Entity Framework 4.1.

This simple tutorial still applies today, I just did it with Visual Studio 2013 so that would be MVC5 and Entity Framework 6.  There are just a couple gotchas.

Generating Strongly Typed Entity Class

This is the first gotcha.  I picked the EF 6.x DbContext Generator.  Then I discovered that the Model1.Context was redundant so I had to delete it.  I kept the Model1.tt though.

Running the Application

This one was really easy to fix.  In the Global.asax you will find that MVC5 uses the various config.cs files located in the App_Start folder.  So instead of editing your routes in Global.asax just edit them in RouteConfig.cs in the App_Start folder.

There might be better ways to fix these gotchas, especially that first one.  The thing is it worked and is a great little DB First tutorial.

MVC Regex Phone Numbers and Emails

This is just a quick bit on Phone Numbers and Emails in MVC.  Well, at least MVC3.  The [DataType(DataType.PhoneNumber, ErrorMessage = “You must provide a valid phone number.”)] and [DataType(DataType.EmailAddress, ErrorMessage = “You must provide a valid email address.”)] apparently does not perform the actual validation for you.  Don’t fret though, you can add the RegularExpression annotation to it.

Here are two examples, you can use any regex expression, these worked for my needs.  I also left some other annotations in there.

[Required(AllowEmptyStrings = false, ErrorMessage = "You must provide a supervisor email.")]
[StringLength(50, ErrorMessage = "A supervisor email cannot exceed 50 characters.")]
[Display(Name = "Supervisor Email")]
[DataType(DataType.EmailAddress, ErrorMessage = "Please enter a valid supervisor email address.")]
[RegularExpression("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", ErrorMessage = "You must provide a valid supervisor email address.")]
public string SupervisorEmail { get; set; }

[Required(AllowEmptyStrings = false, ErrorMessage = "You must provide your home phone number.")]
[Display(Name = "Home Phone")]
[DataType(DataType.PhoneNumber, ErrorMessage = "You must provide a proper phone number.")]
[RegularExpression("^\\D?(\\d{3})\\D?\\D?(\\d{3})\\D?(\\d{4})$", ErrorMessage = "You must provide a proper phone number.")]
public string HomePhone { get; set; }

The WebGrid In MVC

Something that new comers to MVC may wonder about, is how to create something like a GridView in MVC.  I know this was something I ran into, but quickly found the answer.  Meet the WebGrid.  The WebGrid is just that, it will create a grid of your tabular data to display nice and neatly on your view.

To make use of a WebGrid you have to perform two basic steps; new up a WebGrid object, and invoke that object’s GetHtml method.

When we new up a WebGrid we can provide some basic details for it.  Things like the source of the data, the columns you will display. how many rows per page, if it allows paging and if it allows sorting.  Lets provide an example,this example uses a model that contains: EmployeeName, SupervisorName, and Submitted.

Read the rest of this entry

MVC3 Custom Validation

I’m still trying to find the time to truly learn MVC.  I know I like it better than web forms, it is just a matter of spending the quality time with it at home and at work to get as comfortable with it as I am with web forms.  One area that I could not find the answer to, and kept pushing back for later, is custom validation.  I found many examples of doing custom validation where you hard code some value, but that isn’t what I wanted.  I wanted to do custom validation based on a field being unique in a database and have it work with the DataAnnotations and the whole Html.ValidationMessageFor in Razor.

So, after spending some time focused on it I figured it out.  It really isn’t that hard at all.  In a nutshell you create a new class that implements the ValidationAttribute; this class will do the actual work.  Then you add your new attribute to your model.  Of course I’ll include a simple example.

Assumptions of my example.  I have a table called tblTitle, it contains id, name, and isValid fields.  My project uses Entity Framework.  I create a class to handle my business logic and a class that will act like my model.  I also decorate my model class with appropriate DataAnnotations.  I have a controller, which checks for the model state to be valid before calling the business logic’s update or create method. My business logic class also contains the method to check for a unique name.

We want our name field in the title table to be unique inside that table.  No need to have multiple versions of the same title right?

Read the rest of this entry

Using A Static Class In MVC3

How do I reference a static class in my MVC3 project?

A simple question which actually has a very simple answer, but finding that answer may not be too simple.  In Web Forms we are used to putting these things in the App_Code folder.  Sure you can create one in MVC3 but it doesn’t work like Web Forms.

I remembered a video I watched, probably by John Papa, that mentioned using a Helpers folder.  Sure it was for Silverlight but hey, MVC has helpers too.  So I tried that and it worked!  Now keep in mind that you don’t have to name it Helpers.  Just create a normal folder, give it a meaningful name and stick your stuff in there.  Just like you do with Controllers, Models, and Views.  Also note that you can add a using to the top of the page where you are referencing it (sorry, I’m a C# guy, I’ve not done VB since VB5 or VB6).

Adding A New jQuery Theme To MVC3

Today we will add a new jQuery theme to a new MVC3 project. I know I am still new to this, but I felt this one needed its own posting.

The first thing you need to do is obtain a jQuery theme. You don’t have to make a custom one, but if you do the same procedure applies. So head over to jQuery UI ThemeRoller and get yourself a theme.  For me, I am going to get Eggplant.  At the time of this writing the version I am downloading is 1.8.20.  Also to keep things easy I am just pulling down the whole thing.

Read the rest of this entry