Is it possible to pass ModelExpression to a TagHelper?

冷暖自知 提交于 2019-12-10 04:26:43

问题


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 wich has a ModelExpression property:

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

Everytime I try to pass it, the Model expression is For from TemplateViewModel, not the real Expression wich 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 literaly 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 motiviation is to create a single <form-group for="" /> TagHelper, which is generating a Bootstrap Form Group.


回答1:


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; }?



来源:https://stackoverflow.com/questions/47125008/is-it-possible-to-pass-modelexpression-to-a-taghelper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!