For example:
Html.TextBoxFor(x => x.ModelProperty)
If I were to get an expression like this as a method argument, how would I get the referenced property from the expression? My experience with expressions is somewhat limited and based on what I know, I don't get how this works.
In MVC, HTML Helper can be considered as a method that returns you a string. This string can describe the specific type of detail of your requirement. Example: We can utilize the HTML Helpers to perform standard HTML tags, for example HTML<input>, and any <img> tags.
There are two ways in MVC to create custom Html helpers as below. We can create our own HTML helper by writing extension method for HTML helper class. These helpers are available to Helper property of class and you can use then just like inbuilt helpers. Add new class in MVC application and give it meaningful name.
Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.
You can get property name easily like this:
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var propName = metadata.PropertyName;
Or you can get property and its attributes:
MemberExpression memberExpression = (MemberExpression) expression.Body;
var member = memberExpression.Member as PropertyInfo;
var attributes = member.GetCustomAttributes();
For example you can write a simple method that generates a input element like this:
public static MvcHtmlString TextboxForCustom<TModel, TResult>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TResult>> expression)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var propName = metadata.PropertyName;
StringBuilder sb = new StringBuilder();
sb.AppendFormat("<input type=\"text\" id=\"{0}\" />", propName);
return MvcHtmlString.Create(sb.ToString());
}
Take a look at my answer here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With