Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass ModelExpression to a TagHelper?

We can get a ModelExpression using this property in a TagHelper:

[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }

I somehow managed* to have a ViewModel which has a ModelExpression property:

public class TemplateViewModel
{
    public ModelExpression For { get; set; }
}

Every time I try to pass it, the Model expression is For from TemplateViewModel, not the real Expression which is stored into For:

@model TemplateViewModel
<input asp-for="@Model.For" class="form-control"/>

Above results in:

<input class="form-control" type="text" id="For" name="For" value="Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression" />

I expected, the input, which is described by the ModelExpression instead of literally a ModelExpression for the ModelExpression.

*since I want to have a Template View for an TagHelper using IHtmlHelper::PartialView(). This example is heavy minimized. My main motivation is to create a single <form-group for="" /> TagHelper, which is generating a Bootstrap Form Group.

like image 301
Christian Gollhardt Avatar asked Nov 05 '17 18:11

Christian Gollhardt


1 Answers

ModelExpression is handled as a special case in the Razor Compiler, so this isn't going to work directly. Since the compiler is open source, you could suggest a patch to ignore cases where the property is itself a ModelExpression. In the mean time, you're going to need to use a different type of property in your tag helper, to help you get a reference to the actual ModelExpression. Perhaps public Func<ModelExpression> ForAccessor { get; set; }?

like image 96
Jeremy Lakeman Avatar answered Oct 04 '22 16:10

Jeremy Lakeman