Tags: , , , , , , , , , | Categories: ASP.Net, C#, MVC, Razor, HTML, HtmlHelper extensions Posted by Scott on 1/6/2012 6:42 PM | Comments (0)

So, we want a way to bind an HTML <select> to an enum, each enum value becoming an <option>. We also want to be able to hide some of the enum values from the <select> so that we can allow existing data to function but stop new data from using these values.

We start by creating an attribute that we can decorate our enum with, marking values as in use or not. If we don't add the attribute the assumption is that all the values of the enum are still in use which saves the effort of updating every enum in the application domain.

public class EnumBindingAttribute : Attribute
{
    public bool IsInUse { get; set; }
}

Then we decorate the enum with the new attribute.

public enum ContactNumberType
{
    [EnumBinding(IsInUse=false)]
    Unknown,
    [EnumBinding(IsInUse = true)]
    Home,
    [EnumBinding(IsInUse = true)]
    Work,
    [EnumBinding(IsInUse = true)]
    Mobile,
    [EnumBinding(IsInUse = false)]
    Fax,
    [EnumBinding(IsInUse = false)]
    Other
}

Now, to bind the enum to the <select> we have an extension to HtmlHelper. This emits a <select> tag with id and name attributes and then enumerates the additional attributes specified in the dictionary, adding each in turn. These additional attributes are essential for aria- and data- which you'll probably be using. Next comes the fun - reflection. We enumerate each of the values in the enum, test for the existence of the EnumBindingAttribute and skip any that have the attribute set to false. For those that we are rendering we check for a DescriptionAttribute and use that if it's present otherwise we render out the enum as a string. If the value of the enum matches the selectedValue parameter we add the selected attribute to the <option> tag.

public static MvcHtmlString DropDownListEnum<T>(this HtmlHelper helper, string name, Type enumeration, string selectedValue, Dictionary<string, object> htmlAttributes)
{
    StringBuilder output = new StringBuilder();
    output.AppendFormat("<select id=\"{0}\" name=\"{0}\"", name);
    foreach (var attribute in htmlAttributes)
    {
        if (attribute.Value != null)
        {
            output.AppendFormat(" {0}=\"{1}\"", attribute.Key, attribute.Value);
        }
        else
        {
            output.AppendFormat(" {0}", attribute.Key);
        }
    }

    output.Append(" >");
    foreach (var enumValue in enumeration.GetEnumValues())
    {
        FieldInfo fieldInfo = enumeration.GetField(enumValue.ToString());
        EnumBindingAttribute[] enumbindingAttributes = (EnumBindingAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumBindingAttribute), false);
        if (!enumbindingAttributes.Any() || enumbindingAttributes.Any(e => e.IsInUse)) // no attribute set implies is in use
        {
            int enumIntValue = (int)enumValue;
            output.Append("<option");
            if (selectedValue == enumIntValue.ToString())
            {
                output.Append(" selected=\"selected\"");
            }

            output.AppendFormat(" value=\"{0}\">", enumIntValue.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes.Any())
            {
                output.Append(attributes[0].Description);
            }
            else
            {
                output.Append(enumValue.ToString());
            }

            output.Append("</option>");
        }
    }

    output.Append("");
    return MvcHtmlString.Create(output.ToString());
}

Now we just use the HtmlHelper extension!

@model ContactNumber
@using (Html.BeginForm("UpdateContactNumber", "Members", null, FormMethod.Post, null))
{
    @Html.HiddenFor(m => m.Id)
    
Contact Numbers @Html.DropDownListEnum("ContactNumberType", typeof(ContactNumberType), Model == null ? "0" : ((int)Model.ContactNumberType).ToString(), new Dictionary<string, object> { { "aria-required", "true" }, { "aria-labelledby", "ulblType" }, { "required", null } })
}
Tags: , , , , , , , , , , | Categories: ASP.Net, C#, MVC, NHibernate, Razor Posted by Scott on 12/19/2011 10:53 AM | Comments (1)

We keep discussing what use a view model has and where (if at all) we should be using them. Eventually we came to some conculsions, not all of which are obvious.

Firstly a view model is important to keeping your views clean; it should provide all of the data required by a view - this avoids calling entity managers from within a view to get (for arguements sake) the list of orders for a customer. Putting this kind of code in your views is bad; it puts business logic into a file that should be exclusively UI logic, it puts executable code into a file that is not (usually) compiled, it puts code beyond the reach of (most) refactoring tools and, it creates a very confusing document.

Secondly a view model provides a buffer between our domain models and our web application - yes, our web application does have visibility of the domain models and an api via the entity manager to CRUD the entities but, should an entity be forced to implement a parameterless constructor so that binding can take place? Or (as in our case) should our protected internal parameterless .ctor (written for the exclusive use of NHibernate) now become public and therefore bypass some of the business logic that is implemented within the parameterised .ctors?

Clearly the answer is no but we can create a view model within our application that mirrors the domain model and provides the required parameterless .ctor, binding can take place, validation can happen and the only cost is calling the parameterised .ctor on the domain model, passing in the values from the view model.

Let's explain this with an example. Firstly, our domain class Client, note that the default parameterless .ctor is protected internal so it will not be available within our MVC application and therefore not available to MVC model binding. The public .ctor implements our business logic that all clients must have a forename and surname (this could be further enhanced within the .ctor by adding validation errors if either forename or surname are null or empty).

namespace Playground.Models
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using NHibernate.Validator.Constraints;

    public class Client : BaseEntity
    {
        private IList<ClientEmailAddress> emailAddresses = new List<ClientEmailAddress>();
        private IList<ClientTelephoneNumber> telephoneNumbers = new List<ClientTelephoneNumber>();

        // public .ctor requires forename and surname
        public Client(string forename, string surname)
        {
            this.Forename = forename;
            this.Surname = surname;
        }

        // internal .ctor for NHibernate. Never expose this publically.
        protected internal Client() { }

        // NotNullNotEmpty attribute from NHibernate.Validation.Constraints
        [NotNullNotEmpty()]
        public virtual string Forename { get; set; }

        // NotNullNotEmpty attribute from NHibernate.Validation.Constraints
        [NotNullNotEmpty()]
        public virtual string Surname { get; set; }

        public virtual IList<ClientEmailAddress> EmailAddresses
        {
            get { return this.emailAddresses; }
            private set { this.emailAddresses = value; }
        }

        public virtual IList<ClientTelephoneNumber> TelephoneNumbers
        {
            get { return this.telephoneNumbers; }
            private set { this.telephoneNumbers = value; }
        }
    }
}

So, what do we do within our MVC application that wants to perform CRUD operations on our Client type? Well, we could use the type directly within our MVC controller:

namespace Playground.Web.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Playground.BusinessLogic;
    using Playground.Models;

    public class ClientController : Controller
    {
        [HttpGet]
        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(string forname, string surname)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            Client client = new Client(forename, surname);
            client = this.entityManager.Save(client);
            if (client.ValidationErrors.Any() || client.OperationErrors.Any())
            {
                foreach (var validationError in client.ValidationErrors)
                {
                    ModelState.AddModelError(validationError.Property, validationError.Error);
                }

                foreach (var operationError in client.OperationErrors)
                {
                    ModelState.AddModelError(operationError.Operation, operationError.Error);
                }

                return View();
            }

            return RedirectToAction("Index");
        }
    }
}

The issue with this approach is that checking the ModelState.IsValid property really doesn't do anything and we're all the way into the Save method before we get any validation of our object. And when we do validate we're pulling business (or possibly database) errors and their not-so-user-friendly messages into our UI. The typical solution is to use the domain model for the parameter on the post method of the controller (and as the model in the view) which automagically wires up form values with properties on the model. This type of model binding requires a default parameterless .ctor which now doesn't exist because it would break the business rules on the Client type.

So what we really want is to use types throughout our MVC application, use binding within our controllers and, not break our business rules. If we create a model within our MVC application - a view model - we can solve our issue and get early validation with user friendly messages into the bargin. Note the namespace and the implicit default parameterless .ctor.

namespace Playground.Web.ViewModels
{
    using System; 
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;

    public class Client
    {
        // Required is from the System.ComponentModel.DataAnnotations namespace.
        [Required(ErrorMessage="This is a user friendly validation message")]
        public virtual string Forename { get; set; }

        [Required()]
        public virtual string Surname { get; set; }
    }
}

Now we can update our controller to use our view model:

namespace Playground.Web.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Playground.BusinessLogic;
    using Playground.Models;

    public class ClientController : Controller
    {
        [HttpGet]
        public ActionResult Add()
        {
            return View(new Playground.Web.ViewModels.Client());
        }

        [HttpPost]
        public ActionResult Add(Playground.Web.ViewModels.Client postedClient)
        {
            if (!ModelState.IsValid)
            {
                return View(postedClient);
            }

            Client client = new Client(postedClient.Forename, postedClient.Surname);
            client = this.entityManager.Save(client);
            if (client.ValidationErrors.Any() || client.OperationErrors.Any())
            {
                foreach (var validationError in client.ValidationErrors)
                {
                    ModelState.AddModelError(validationError.Property, validationError.Error);
                }

                foreach (var operationError in client.OperationErrors)
                {
                    ModelState.AddModelError(operationError.Operation, operationError.Error);
                }

                return View(postedClient);
            }

            return RedirectToAction("Index");
        }
    }
}

Now when we check ModelState.IsValid we're checking the attributes for the view model before we try to save the domain object.We also get the advantage of using model binding with the view like this:

@model Playground.Web.ViewModels.Client

@{
    ViewBag.Title = "Add";
}

Add

@using (Html.BeginForm()) { @Html.ValidationSummary(true)
Client
@Html.LabelFor(model => model.Forename)
@Html.EditorFor(model => model.Forename) @Html.ValidationMessageFor(model => model.Forename)
@Html.LabelFor(model => model.Surname)
@Html.EditorFor(model => model.Surname) @Html.ValidationMessageFor(model => model.Surname)

}
@Html.ActionLink("Back to List", "Index")

And we have the advantage where we can add properties to the view model that aren't required on the domain model; the user input on a registration form might require the password to be confirmed (an attempt at mitigating typos resulting in the user setting their password incorrectly) so a ConfirmPassword property can be added to the view model together with a validator but the domain model need not be sullied with this non-persisted, UI only property.

Tags: , , , , , , | Categories: ASP.Net, C#, Fluent, MVC, NHibernate, Ninject, NHibernate,Validator Posted by Admin on 9/14/2011 4:26 PM | Comments (0)

Eventually (after lots of google searches and putting together snippets from here, there and, everywhere) we now have Fluent NHibernate, NHibernate.Validator and Ninject all playing together.

First, we configure NHibernate using Fluent NHibernate passing the configuration to NHibernate.Validator so that it can configure the NHibernateSharedEngineProvider - this is important as Ninject will use the NHibernateSharedEngineProvider.

public static class Database
{
    private static ISessionFactory sessionFactory = null;

    public static ISessionFactory CreateSessionFactory()
    {
        var config = new AutoMappingConfiguration();
        ValidatorEngine validatorEngine = null;
        if (sessionFactory == null)
        {
                sessionFactory = Fluently
                .Configure()
                .Database(
                    MsSqlConfiguration
                    .MsSql2008
                    .ConnectionString(c => c.Server("").Database("").TrustedConnection()))
                .Mappings(
                    m => m.AutoMappings.Add(
                        AutoMap.AssemblyOf<EntityBase>(config)
                        .Override<EntityBase>(n => n.IgnoreProperty(c => c.ValidationErrors))
                        .Override<Country>(n => n.IgnoreProperty(c => c.DisplayName))
                        ))
                .ExposeConfiguration(c => { 
                    validatorEngine = ConfigureNHibernateValidator(c); 
                    BuildSchema(c); 
                })
                .BuildSessionFactory();
        }

        return sessionFactory;
    }

    public static ValidatorEngine ConfigureNHibernateValidator(Configuration nhibernateConfiguration)
    {
        NHibernate.Validator.Cfg.Environment.SharedEngineProvider = new NHibernateSharedEngineProvider();
        var validatorConfiguration = new NHibernate.Validator.Cfg.Loquacious.FluentConfiguration();
        validatorConfiguration
            .SetDefaultValidatorMode(ValidatorMode.UseAttribute)
            .Register(Assembly.Load("models").ValidationDefinitions())
            .IntegrateWithNHibernate
            .ApplyingDDLConstraints()
            .RegisteringListeners();
        var validatorEngine = NHibernate.Validator.Cfg.Environment.SharedEngineProvider.GetEngine();
        validatorEngine.Configure(validatorConfiguration);
        ValidatorInitializer.Initialize(nhibernateConfiguration, validatorEngine);
        return validatorEngine;
    }

    private static void BuildSchema(Configuration config)
    {
        new SchemaUpdate(config).Execute(false, true);
    }
}

Then we configure Ninject

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IEntityManager>().To<EntityManager>().InRequestScope();
    kernel.Bind<ISessionFactory>().ToMethod(x => Database.CreateSessionFactory()).InSingletonScope();
    kernel.Bind<ISession>().ToMethod(x => kernel.Get<ISessionFactory>().OpenSession()).InRequestScope();
    kernel.Bind<ISharedEngineProvider>().ToMethod(x => NHibernate.Validator.Cfg.Environment.SharedEngineProvider).InSingletonScope();
}

Then we inject both ISession and ISharedEngineProvider into our EntityManager via the .ctor. We then check the Entity is valid before saving.

public class EntityManager : IEntityManager
{
    private ISession session = null;
    private ISharedEngineProvider validator = null;

    public EntityManager(ISession session, ISharedEngineProvider validator)
    {
        this.session = session;
        this.validator = validator;
    }

    public T Save<T>(T item) where T : EntityBase
    {
        item.ValidationErrors.Clear();
        ValidatorEngine ve = this.validator.GetEngine();
        if (!ve.IsValid(item))
        {
            foreach (var invalidValue in ve.Validate(item))
            {
                item.ValidationErrors.Add(new ValidationError() { PropertyName = invalidValue.PropertyName, Message = invalidValue.Message });
            }
        }
        else
        {   
            try
            {
                this.session.SaveOrUpdate(item);
                this.session.Flush();
            }
            catch (InvalidStateException ise)
            {
                item.ValidationErrors.Clear();
                foreach (var invalidValue in ise.GetInvalidValues())
                {
                    item.ValidationErrors.Add(new ValidationError() { PropertyName = invalidValue.PropertyName, Message = invalidValue.Message });
                }
            }
        }

        return item;
    }
}

Note that within EntityManager we use ISharedEngineProvider.GetEngine() to get our pre-configured Validator. The try { ... } catch { ... } around this.Session.SaveOrUpdate(item) isn't really required but better to be safe than sorry!

Tags: , , , , | Categories: ASP.Net, C#, Javascript, MVC, Razor Posted by Admin on 6/15/2011 2:24 PM | Comments (2)

Sometimes you just want your javascript to execute after the page is loaded, simply put your <script> block just before your </body> tag and you're done. But if your page is made up of a layout, view and various partial views then this is how to keep those script calls at the end of the page and have them fire in the correct order.

Add these methods to your extension methods class (or create one).

public static MvcHtmlString AddScript(this HtmlHelper htmlHelper, Func<object, HelperResult> script, int executionSequence = int.MaxValue)
{
    Dictionary<int, List<Func<object, HelperResult>>> scripts = new Dictionary<int, List<Func<object, HelperResult>>>();
    if (htmlHelper.ViewContext.HttpContext.Items["_scripts_"] != null)
    {
        scripts = htmlHelper.ViewContext.HttpContext.Items["_scripts_"] as Dictionary<int, List<Func<object, HelperResult>>>;
    }

    if (!scripts.ContainsKey(executionSequence))
    {
        scripts.Add(executionSequence, new List<Func<object, HelperResult>>());
    }

    scripts[executionSequence].Add(script);
    htmlHelper.ViewContext.HttpContext.Items["_scripts_"] = scripts;
    return MvcHtmlString.Empty;
}

public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
{
    foreach (object key in htmlHelper.ViewContext.HttpContext.Items.Keys)
    {
        if (key.ToString() == "_scripts_")
        {
            var scripts = htmlHelper.ViewContext.HttpContext.Items[key] as Dictionary<int, List<Func<object, HelperResult>>>;
            foreach (var index in scripts.Keys.OrderBy(x => x))
            {
                foreach (var script in scripts[index])
                {
                    var template = script as Func<object, HelperResult>;
                    if (template != null)
                    {
                        htmlHelper.ViewContext.Writer.Write(template(null));
                    }
                }
            }
        }
    }

    return MvcHtmlString.Empty;
}

Call AddScript in your views and partials

<h2 id="indexHeader">Index</h2>
@Html.AddScript(
@<text>
    jQuery('#indexHeader').css('font-size', '18em');
</text>, 1)

Call RenderScripts in your layout.

<body>
    @RenderBody()
    <script>
        @Html.RenderScripts()
    </script>
</body>
Tags: , , , , , , | Categories: ASP.Net, C#, MVC, NHibernate, Ninject Posted by Admin on 6/13/2011 12:55 PM | Comments (7)

We eventually managed to get Ninject,Fluent NHibernate, NHibernate.Linq and MVC3 to play nicely together. Each of these libraries has its issues when it comes to playing nicely mainly due to dependencies mis-matches or due to a lack of instruction.

Firstly, Ninject. We installed Ninject into our sample application using the Package Manager Console.

Install-Package Ninject
Install-Package Ninject.Web
Install-Package Ninject.MVC3

We missed Ninject.MVC3 first time around which cost us about two hours of head scratching so remember to install it.

Once all three Ninject libraries are installed into your application you should have a new generated file App_Start/NinjectMVC3.cs, this is where you load your Ninject Module(s) into your application and where the magic construction injection takes place for your controllers (amongst other things).

The next step seems to be widely documented on the net pointless if you're using NinjectMVC3; modifying your Global.asax file to enable Ninject to do its thing is no longer required and to configure NHibernate fluently.

public class MvcApplication : HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Person", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }
}

Next we need to configure Ninject so that it knows what concrete implementations of interfaces to inject. This is done by inheriting from NinjectModule and overriding the Load() method.

public override void Load()
{
    this.Bind<IRepository>().To<NHRepository>().InRequestScope(); //.InSingletonScope(); <-- Singleton scope doesn't work with ISession in request scope!
    this.Bind<ISessionFactory>().ToMethod(x => Database.CreateSessionFactory()).InSingletonScope();
    this.Bind<ISession>().ToMethod(x => context.Kernel.Get<ISessionFactory>().OpenSession()).InRequestScope();
    this.Bind<PersonController>().ToSelf();
}

In this case whenever a constructor requires an implementation of IRepository the same an instance of NHRepository is supplied by the InSingletonScope modifier. We're also binding our NHibernate ISession to the GetCurrentSessionOpenSession() method of the ISessionFactory (which being static prevents re-initialization of SessionFactory - a very expensive operation) and binding the PersonController to itself.

Finally we need Ninject to load our module into the application when the application starts, this is done in NijnectMVC.cs by modifying the CreateKernel method.

private static IKernel CreateKernel()
{
    var kernel = new StandardKernel(new MvcApplicationNinjectModule());
    RegisterServices(kernel);
    return kernel;
}

As far as Ninject is concerned we're all sorted. We just need to create IRepository and implement this in NHRepository which is where NHibernate.Linq comes into the mix and then create our controller to call the repository.

We won't go into the details of IRepository and NHRepository other than to point out that Ninject injects our NHibernate Session into NHRepository in the constructor.

public interface IRepository
{
    IQueryable<T> Get<T>();
    IQueryable<T> Get<T, TKey>(params OrderByClause<T, TKey>[] orderBy);
    IQueryable<T> Get<T>(int pageSize, int pageIndex, out int recordCount);
    IQueryable<T> Get<T, TKey>(int pageSize, int pageIndex, out int recordCount, params OrderByClause<T, TKey>[] orderBy);
}
public class NHRepository : IRepository
{
private ISession session = null;

public IQueryable<T> Get<T>()
{
    return this.session.Query<T>();
}

public IQueryable<T> Get<T, TKey>(params OrderByClause<T, TKey>[] orderBy)
{
    var query = this.session.Query<T>();
    foreach (var order in orderBy)
    {
        switch (order.Direction)
        {
            case OrderByDirection.Descending:
                query = query.OrderByDescending(order.Expression);
                break;
            default:
                query = query.OrderBy(order.Expression);
                break;
        }
    }

    return query;
}

public IQueryable<T> Get<T>(int pageSize, int pageIndex, out int recordCount)
{
    recordCount = this.session.Query<T>().Count();
    return this.session.Query<T>().Skip(pageSize * pageIndex).Take(pageSize);
}

public IQueryable<T> Get<T, TKey>(int pageSize, int pageIndex, out int recordCount, params OrderByClause<T, TKey>[] orderBy)
{
    recordCount = this.session.Query<T>().Count();
    var query = this.session.Query<T>();
    foreach (var order in orderBy)
    {
        switch (order.Direction)
        {
            case OrderByDirection.Descending:
                query = query.OrderByDescending(order.Expression);
                break;
            default:
                query = query.OrderBy(order.Expression);
                break;
        }
    }

    return query.Skip(pageSize * pageIndex).Take(pageSize);
}

public NHRepository(ISession session)
{
    this.session = session;
}

Finally we come to the controller which needs an instance of IRepository to fetch its data from.

public class PersonController : Controller
{
    private IRepository repository;

    public PersonController(IRepository repository)
    {
        this.repository = repository;
    }

    [HttpGet]
    public ActionResult Index(int? pageIndex)
    {
        int actualPageIndex = pageIndex.GetValueOrDefault(0);
        int recordCount = 0;
        var people = this.repository.Get(10, actualPageIndex, out recordCount, new OrderByClause(c => c.DateOfBirth.Value, OrderByDirection.Descending), new OrderByClause(c => c.Surname, OrderByDirection.Ascending), new OrderByClause(c => c.Forename, OrderByDirection.Ascending));
        int pageCount = (int)Math.Ceiling((double)recordCount / 10);
        return View(new PagedListViewModel(people.ToList(), actualPageIndex, pageCount));
    }

}

Ninject is again doing its magic by injecting an (singleton) instance of NHRepository into our constructor for us.

So where were the issues? Well if you use the package manager to get all the Fluent NHibernate and NHibernate.Linq libraries you'll see that Fluent NHibernate uses version 3.1 of NHibernate but NHibernate.Linq is complied against version 2.1, and NHibernate.Linq is complied against version 3.5 of System.Xml.Linq whereas our application is using version 4.0. To fix these mis-matches we can configure our application to substitute any request for a dependancy with a newer version of the same library. This is done in web|app.config

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
      <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="System.Xml.Linq" publicKeyToken="b77a5c561934e089" />
      <bindingRedirect oldVersion="1.0.0.0-3.5.0.0" newVersion="4.0.0.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="NHibernate" publicKeyToken="aa95f207798dfdb4" />
      <bindingRedirect oldVersion="2.1.0.4000-2.1.2.4000" newVersion="3.1.0.4000" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>
Tags: , , , | Categories: ASP.Net, C#, MVC, Razor Posted by Admin on 5/4/2011 9:06 AM | Comments (4)

To define a method within a razor (cshtml) file. Very useful for recursive rendering of data trees.

@model ListOfItemsViewModel

@if (Model.Items.Any())
{
    <ul>
    @foreach(var item in Model.Items)
    {
        @RenderItem(item);
    }
    </ul>
}

@helper RenderItem(Item item)
{
    @MvcHtmlString.Create(string.Format"<li>{0}", item.Name)
    if (item.Children.Any())
    {
        @MvcHtmlString.Create("<ul>")
        foreach(var childItem in itemChildren)
        {
            @RenderItem(childItem);
        }
        @MvcHtmlString.Create("</ul>")
    }
    @MvcHtmlString.Create("</li>");
}