using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq.Expressions; using Microsoft.AspNet.Mvc.Core; using Microsoft.AspNet.Mvc.ModelBinding; using Microsoft.AspNet.Mvc.Rendering.Expressions; namespace Microsoft.AspNet.Mvc.Rendering { public class HtmlHelper : HtmlHelper, IHtmlHelper { /// /// Initializes a new instance of the class. /// public HtmlHelper([NotNull] IViewEngine viewEngine, [NotNull] IModelMetadataProvider metadataProvider) : base(viewEngine, metadataProvider) { } /// public new ViewDataDictionary ViewData { get; private set;} public override void Contextualize([NotNull] ViewContext viewContext) { if (viewContext.ViewData == null) { throw new ArgumentException(Resources.FormatPropertyOfTypeCannotBeNull( "ViewData", typeof(ViewContext)), "viewContext"); } ViewData = viewContext.ViewData as ViewDataDictionary; if (ViewData == null) { // viewContext may contain a base ViewDataDictionary instance. So complain about that type, not TModel. throw new ArgumentException(Resources.FormatArgumentPropertyUnexpectedType( "ViewData", viewContext.ViewData.GetType().FullName, typeof(ViewDataDictionary).FullName), "viewContext"); } base.Contextualize(viewContext); } public HtmlString DisplayFor([NotNull] Expression> expression, string templateName, string htmlFieldName, object additionalViewData) { var metadata = ExpressionMetadataProvider.FromLambdaExpression(expression, ViewData, MetadataProvider); return GenerateDisplay(metadata, htmlFieldName ?? ExpressionHelper.GetExpressionText(expression), templateName, additionalViewData); } /// public HtmlString NameFor([NotNull] Expression> expression) { var expressionName = GetExpressionName(expression); return Name(expressionName); } /// public HtmlString TextBoxFor([NotNull] Expression> expression, string format, IDictionary htmlAttributes) { var metadata = GetModelMetadata(expression); return GenerateTextBox(metadata, GetExpressionName(expression), metadata.Model, format, htmlAttributes); } protected string GetExpressionName([NotNull] Expression> expression) { return ExpressionHelper.GetExpressionText(expression); } protected ModelMetadata GetModelMetadata([NotNull] Expression> expression) { var metadata = ExpressionMetadataProvider.FromLambdaExpression(expression, ViewData, MetadataProvider); if (metadata == null) { var expressionName = GetExpressionName(expression); throw new InvalidOperationException(Resources.FormatHtmlHelper_NullModelMetadata(expressionName)); } return metadata; } public HtmlString ValueFor(Expression> expression, string format) { var metadata = GetModelMetadata(expression); return GenerateValue(ExpressionHelper.GetExpressionText(expression), metadata.Model, format, useViewData: false); } } }