How can I get an Id from an existing Model Expression in AspNetCore?

Viewed 228

I'm trying to build a view component in a Asp.Net Core 3.1 that takes a model expression as the model.

I have the following view for which the Model is a ModelExpression. How do I get an id the same way @Html.IdFor(m => expr) would?

@model Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression
<input id="*****" name="@Model.Name" type="text" class="form-control" />
1 Answers

The aspnetcore source shows:

        public string IdFor<TResult>(Expression<Func<TModel, TResult>> expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            return GenerateId(GetExpressionName(expression));
        }

Since IdFor actually generates the name and then converts to an id. One would can simply do GenerateId which is exposed via Id

@model Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression
<input id="@Html.Id(Model.Name)" name="@Model.Name" type="text" class="form-control" />
Related