Search code examples
asp.net-corerazorasp.net-core-viewcomponent

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


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" />

Solution

  • 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" />