// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Razor.Internal;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Mvc.Razor
{
///
/// Represents the properties and methods that are needed in order to render a view that uses Razor syntax.
///
/// The type of the view data model.
public abstract class RazorPage : RazorPage
{
private IModelMetadataProvider _provider;
///
/// Gets the Model property of the property.
///
public TModel Model
{
get
{
return ViewData == null ? default(TModel) : ViewData.Model;
}
}
///
/// Gets or sets the dictionary for view data.
///
[RazorInject]
public ViewDataDictionary ViewData { get; set; }
///
/// Returns a instance describing the given .
///
/// The type of the result.
/// An expression to be evaluated against the current model.
/// A new instance describing the given .
///
///
/// Compiler normally infers from the given .
///
public ModelExpression CreateModelExpression(Expression> expression)
{
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
if (_provider == null)
{
_provider = Context.RequestServices.GetRequiredService();
}
var name = ExpressionHelper.GetExpressionText(expression);
var modelExplorer = ExpressionMetadataProvider.FromLambdaExpression(expression, ViewData, _provider);
if (modelExplorer == null)
{
throw new InvalidOperationException(
Resources.FormatRazorPage_NullModelMetadata(nameof(IModelMetadataProvider), name));
}
return new ModelExpression(name, modelExplorer);
}
}
}