Validation and Updating UI Values Based on User Input in MVC 3 Razor

I’m currently working on a project leveraging ASP.NET MVC 3 and the Razor View Engine. Wow, that’s a mouth full! This is some pretty awesome stuff. I’ve been extremely impressed with the capabilities of the framework, and I continue to be impressed the more I use it and learn it.

Remote Validation

One of the coolest features I’ve found in MVC 3 has been remote validation. What is remote validation? It is a way to leverage actions on a controller to validate user input on a model object. To use it you simply apply the RemoteAttribute to the property on your model that will be an input field in a form and specify the action and controller to use. A great example of how this is done can be found here on the msdn. What I like about this is the flexibility to have a validation controller per model on very small projects, or have a dedicated validation controller that calls model validator classes. The controller will only receive the value it should validate so each property should specify a different action on the validation controller regardless of which approach you take. I prefer the model validator approach because it allows me to reuse the validation logic when a form is submitted and I need to do one last validation before the model is persisted.

Updating UI Values Based on User Input

OK, so this sounds very confusing. So let me try to explain what I wanted to do. I have a list of Entry objects and each entry has a property of type EntryDefinition. Some entries are auto generated based on the value chosen for another entry, but all entries are always displayed to the user. If an entry is auto generated it is read only, otherwise it can be modified by the user. I needed a way send values entered by the user to the server, process them and generate the auto generated values, and then display the updated values the user. This was a pain to get working! I discussed the matter with my coworker Kevin Stumpf who has much more experience working in the web world. He helped me get on the right path to solve the matter.

First, was the challenge of getting the values written to the HTML file using Razor. A helpful Stack Overflow post showed me how to render a list of complex objects. Making sure I used Html.HiddenFor for all of the properties that were not displayed to the user took some getting used to. I kept receiving null values on the server side post in my model object and didn’t understand why at first.

Next, I need to get multiple submit buttons on my form. One button for for submitting the form and a new button for sending the model to the server for updating and updating the user’s display. There were a couple of options that I found after reading this post on Stack Overflow. That post linked to this post by Andrey Shchekin, which then led me to the post by David Findley that finally solved the problem best for me. The solution was to set the name property to button for each of the submit buttons. Then set each button’s value property to whatever made sense to the user, in my case “Update” and “Submit.” Then in the action handling the post I add a new parameter of type string named button. This maps to the name of the two buttons. The value the the button parameter will be the value of the button clicked by the user. Now in the action I could check if button equaled “Update” then don’t persist any data, generate any new values and update the model with those values then return View(model) and the user will see the new values and the other values they had input earlier.

After talking more with Kevin he added that I should just hook up to the text changed of the text boxes of the source entries using JQuery then update the auto generated values automatically as the user types. This would be awesome! If there is enough time on the project I will try this.


As I found from my searches there are a ton of articles out there on all this stuff. I just get so excited when I find cool stuff that I like to share. Hopefully something here is useful in your quest!

Dynamic Actions in MVC 3

In MVC 3 you get a lot of stuff for free. Convention determines a lot of the basic stuff. This is very awesome and helps alleviate some of the more mundane and boring work involved with setting up an ASP.NET site. However, with magic comes limitations. In my particular case I need to have an action with an arbitrary number of parameters without the need to have an overload in my controller for each parameter. Lets look at what I’m talking about.

My example is a bit of a stretch, but should help explain what I’m doing. If I have a controller named ContactsController with an action named Find which takes one parameter which is a name, then I could call http://site/Contacts/Find/Jon and this would return the contact with the name Jon. However, if I want an action named CreateGroup which will take in a list of names which will then create a group including all of the people whose names were passed in, I’d need to do http://site/Contacts/CreateGroup/Jon/Holly/Drew/Brian/. What I will be addressing in this blog is how to do this without the need for an overload of CreateGroup for 2, 3, 4, etc. names as parameters.

In the Global.asax file we will need to map the correct routes. If we use the MVC 3 Internet Template in VS2010 then we’ll have the following default route:

	"Default", // Route name
	"{controller}/{action}/{id}", // URL with parameters
	new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

This default route handles the Find action just fine, however it will not work with CreateGroup. We need a way to specify an unlimited number of parameters. In order to accomplish this we need the following route:

//NOTE: This prevents creating routes after this route that have a static number of parameters

What we did here is say that for any given Controller and any given Action use the no parameter Action regardless of how many parameters there are. So in our controller we will now use:

public class ContactsController : Controller
	public ActionResult Find(string id)
		return View();

    public ActionResult CreateGroup(string rawParams)
		var names = rawParams.Split('/');
		//TODO: process names
		return View();

As long as the name of the parameter in the route matches the name of the parameter in the Action we will receive our string of names. After we parse it out we’ll be good to go!

Some Words of Caution

When doing this you cannot have an overloaded Action named CreateGroup. If CreateGroup is overloaded you will get the following error of ambiguity:

The current request for action ‘CreateGroup’ on controller type ‘ContactsController’ is ambiguous between the following action methods:
System.Web.Mvc.ActionResult CreateGroup(System.String) on type Mvc3RazorPoC.Controllers.ContactsController
System.Web.Mvc.ActionResult CreateGroup() on type Mvc3RazorPoC.Controllers.ContactsController

This makes sense in our situation, because we always want to handle all parameters in this one Action.

Also, this should be the last route in the Global.asax file. It will prevent overloaded routes from being fired correctly. If you have an Action that takes in 2 parameters and the route is placed after our dynamic route the dynamic route will kick in and the parameters will not be filled correctly even though the Action will be called correctly. If the 2 parameter routed is above the dynamic routed all will be well and work as expected.