Let's say I have the following input
tag which utilizes the built-in tag helper:
@model ProductViewModel
<label asp-for="Product.Id"></label>
In my case, this expands into the following:
<label for="Product_Id">Id</label>
I see that asp-for
is expecting a ModelExpression
:
In tag helper implementations, I often see a property like the following:
public ModelExpression For { get; set; }
It appears that this is automatically populated when the tag helper is used.
Is there a way to instantiate a ModelExpression
directly in C#?
I.e. something like this:
var exp = new ModelExpression("Product.Id",...)
I'd like to be able to generate "Product_Id" and "Id" from Product.Id
as the input
tag helper did.
As far as I know, you can specify that your property is to be set to the name of some property on the View's Model object by declaring your property with the ModelExpression type. This will enable any developer using your property to get IntelliSense support for entering a property name from the Model object. More importantly, your code will be passed the value of that property through the ModelExpression's Model property.
Sample code as below:
Code in the View page:
Code in the Model
From above code, you can see that we could custom the attribute name. More detail information about using the ModelExpression, check the following links:
Creating Custom Tag Helpers With ASP.NET Core MVC
Expression names
Besides, do you mean you want to change the
Product. Id
toProduct_Id
, in my opinion, I'm not suggesting you change it, because generally we can use "_" as a separator in the property name. So, if we are usingProduct.Id
, it means the Product's Id property, and theProduct_Id
means there have aProduct_Id
property.