Tags: asp.net, c#, mvc, razor, html, select, enum, enumeration, htmlhelper, extension methods |
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)
}
a6842597-5dee-4716-b105-9203d0277ba9|0|.0
Tags: asp.net, c#, mvc, nhibernate, razor, model binding, view models, domain models, nhibernate.validator, dataannotations, validation |
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)
}
@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.
528ce65e-be58-4276-a549-c6f899d7054f|0|.0
So today we were working on a new sample project using NHibernate, Ninject and, ASP.Net MVC3 which (as is usually the case at the start of these things) we wanted to be just right. Typically we ended up with a Client type with its expected lists of phone number and email address, in each list none or one of which can be flagged as being the default. We ended up with a class hierarchy like:
public abstract class BaseEntity
{
public virtual int Id { get; set; }
}
public abstract class BaseEmailAddress
{
public virtual string EmailAddress { get; set; }
public virtual bool IsDefault { get; set; }
}
public class ClientEmailAddress
{
private Client client;
public virtual Client Client
{
get { return this.client; }
private set { this.client = value; }
}
}
public class Client : BaseEntity
{
private IList<ClientEmailAddress> emailAddresses = new List<ClientEmailAddress>();
public virtual IList<ClientEmailAddress> EmailAddresses
{
get { return this.emailAddresses; }
private set { this.emailAddresses = value; }
}
}Everything inherits BaseEntity, ClientEmailAddress inherits BaseEmailAddress which implements the EmailAddress and IsDefault properties.
So then we questioned where do we implement the none or one ClientEmailAddress being flagged IsDefault? We decided that we could shadow the IsDefault property in ClientEmailAddress and implement the logic in the setter; if setting my IsDefault property to true then set the IsDefault property of all the other items in my parents ClientEmailAddresses collection. Like this:
public class ClientEmailAddress
{
private Client client;
public virtual Client Client
{
get { return this.client; }
private set { this.client = value; }
}
public new virtual bool IsDefault
{
get { return base.isDefault; }
set
{
if (value && this.client != null)
{
foreach (var clientEmailAddress in this.client.ClientEmailAddresses)
{
clientEmailAddress.IsDefault = false;
}
}
base.isDefault = value;
}
}
}However, NHibernate did not like this very much, complaining the 'IsDefault is already mapped' or similar which got us to thinking whether the IsDefault property belonged on a BaseEmailAddress type? After some debate we can to the conclusion that the IsDefault property is only relevent to the ClientEmailAddress type since it is only in the context of a list of email addresses that being the default email address makes any sense. So we moved the IsDefault property to the relevent class:
public abstract class BaseEmailAddress
{
public virtual string EmailAddress { get; set; }
}
public class ClientEmailAddress
{
private Client client;
public virtual Client Client
{
get { return this.client; }
private set { this.client = value; }
}
private bool isDefault = false;
public virtual bool IsDefault
{
get { return this.isDefault; }
set
{
if (value && this.client != null)
{
foreach (var clientEmailAddress in this.client.ClientEmailAddresses)
{
clientEmailAddress.IsDefault = false;
}
}
this.isDefault = value;
}
}
}
53cce46f-4add-4b84-a6da-6904e7252445|0|.0
We re-factored a few namespaces and split a few class libraries into multiple assemblies to enable some code re-use but then struggled to automap them using Fluent NHibernate. We quickly noticed that types were being loaded from the different assemblies, but not all of them. It seemed that those types in assembly B that inherited from types in assembly A were not being loaded which in fact was the vast majority of the types in assembly B. We also noticed that other types in assembly B who did not inherit from types in assembly A were also not being loaded. A quick inspection of the inheritance tree showed that only those types in assembly B who inherited from an abstract type were being loaded. In our case the solution was to simple ensure that all the subclasses were defined as abstract types.
// type defined in RealWebDevelopers.Models.dll
namespace RealWebDevelopers.Models
{
public abstract class BaseEntity
{
public int Id { get; set; }
}
}
// type defined in RealWebDevelopers.Models.Jobs.dll
namespace RealWebDevelopers.Models.Jobs
{
using RealWebDevelopers.Models;
public class Advertisement : BaseEntity
{
public string Name { get; set; }
}
}
namespace RealWebDevelopers.Data
{
using RealWebDevelopers.Models;
using RealWebDevelopers.Models.Jobs;
<summary>Loads multiple assemblies into the MappingConfiguration.</summary>
private void MapAssemblies(FluentNHibernate.Cfg.MappingConfiguration config)
{
config.AutoMappings.Add(
AutoMap.Assembly(Assembly.GetAssembly(typeof(BaseEntity)))
.Override<BaseEntity>(a =>
{
a.IgnoreProperty(e => e.OperationErrors);
a.IgnoreProperty(e => e.ValidationErrors);
})
.Conventions.AddFromAssemblyOf<EnumConvention>());
config.AutoMappings.Add(
AutoMap.Assembly(Assembly.GetAssembly(typeof(Advertisement)))
.Override<TokenTransaction>(n => n.Map(c => c.TransactionType).CustomType<int>())
.OverrideAll(a =>
{
a.IgnoreProperty("Display");
})
.Conventions.AddFromAssemblyOf<EnumConvention>());
}
}
301f2af1-9b29-475f-946b-8163497decae|0|.0
So, Country has a collection of Counties
public class Country
{
private IList<County> counties = new List<County>();
public virtual IList<County> Counties
{
get { return this.counties; }
set { this.counties = value; }
}
}
Therefore County has a reference to Country
public class County
{
public virtual Country Country { get; set; }
}
I was trying to create a new County and then add it to the Counties collection of a Country instance
public static void Something()
{
Country country = repository.Get<Country>(countryId);
County county = new County(){ Name = "Berkshire" };
country.Counties.Add(county); //this executes
repository.Save<Country>(country); //this bails
}
The solution was to test the parent Country's County collection within the Country setter of the County class
public class County
{
private Country country = null;
public virtual Country Country
{
get { return this.country; }
set
{
this.country = value;
if (!this.country.Counties.Contains(this))
{
this.country.Counties.Add(this);
}
}
}
}
Why? Well I don't really know, but it works. I guess that there is something going on within NHibernate and object tracking, but that is just a guess!
For a more fluent way of doing the same thing
public class County
{
public virtual Country Country { get; protected set; }
public virtual County WithCountry(Country country)
{
this.country = value;
if (!this.country.Counties.Contains(this))
{
this.country.Counties.Add(this);
}
return this;
}
}
7e6cbe0f-d795-41a8-a6d4-45167941cf0e|0|.0
A while ago we wrote about fluent apis using interfaces, this is probably the 'text book' approach but since we're about real web development lets have a real world approach.
public class Country
{
// backing field for the name property.
private string name = string.Empty;
// backing field for the code property;
private string code = string.Empty;
// accessor to the name backing field. The setter is private.
public string Name
{
get { return this.name; }
private set { this.name = value; }
}
// accessor to the code backing field. The setter is private.
public string Code
{
get { return this.code; }
private set { this.code = value; }
}
// chainable (fluent) method to set the name. Note this returns to instance of the entity whose property is being set.
public Country WithName(string name)
{
this.Name = name;
return this;
}
// chainable (fluent) method to set the code. Note this returns to instance of the entity whose property is being set.
public Country WithCode(string code)
{
this.Code = code;
return this;
}
}
So if we were to use this class within an application we can now write code like
Country unitedKingdom = new Country().WithName("United Kingdom").WithCode("UK");
a9c10815-4932-49f9-8d57-2f1ccff0acf2|0|.0
Tags: asp.net, c#, fluent api, mvc, nhibernate, ninject, nhibernate.validator |
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!
57af47e3-5517-41a7-afa7-d9bd873729a0|0|.0
We tried to write a filter based on a DateTime? (nullable DateTime) property like
IList<Vacancy> vacancies = manager.Get<Vacancy>(v => v.StartDate.GetValueOrDefault(DateTime.MinValue) < DateTime.Today);
But NHibernate (or possibly NHibernate.Linq) threw a runtime error. It turns out that NHibernate(.Linq) handles all this for us so
IList<Vacancy> vacancies = manager.Get<Vacancy>(v => v.StartDate < DateTime.Today);
Works perfectly!
314c30d1-540c-4488-aa1f-2c11261b7992|0|.0
When we wrote NHibernate logical (virtual, 'soft') deletion we showed how to implement virtual deletion of entities (i.e. set IsDeleted = true) by cross-cutting concerns in NHibernate. Since then we've discovered that this raises an issue; when you retrieve a list of entites from NHibernate it doesn't understand that it shouldn't get entites where IsDeleted = true. The initial solution was to add a constraint to our entities (since all our entities subclass BusinessBase we only needed to do this in one place) by adding a Fluent NHibernate Where clause.
public BusinessBaseMap()
{
this.Where("IsDeleted = 0");
this.Id(a => a.Id);
this.Map(a => a.Created);
}Note the string passed to .Where() is SQL.
The constraint did stop deleted entites from being returned but is completely ignored for related collections so you might not get deleted ProductCategories but the Products collection will include deleted Products; not ideal. This caused a little re-think until we realized that this isn't a bug in NHibernate; it isn't the duty of any ORM tool to implement business logic like this - it is the job of the business manager class(es). Needless to say, we left the constraint in place; if NHibernate is going to perform this function for us out-of-the-box we're going to us it!
So back to issue; how to exclude deleted entities from being return in collections? We decided to change our entities collections from 'auto' properties to use backing fields with accessors where the get accessor applies the constraint and NHibernate populates the backing field.
private IList<EmailAddress> emailAddresses = new List<EmailAddress>();
public virtual IList<EmailAddress> EmailAddresses
{
get
{
return this.emailAddresses.Where(a => !a.IsDeleted);
}
}We didn't even need to change our mappings; NHibernate defaults to using a backing field with the name of the property with a lower-case first letter.
ffd0f9e2-d2d5-46a1-8f00-b643eb30a47e|0|.0
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>
d6b7d53b-b8e7-4d69-9daf-4b80c231961e|2|1.0