Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do the MVC html helpers use expressions to get an objects property

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.

like image 639
Nick Daniels Avatar asked Jan 16 '14 20:01

Nick Daniels


People also ask

What is the use of HTML helpers in MVC?

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.

How can create HTML helper in MVC?

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.

What is the main purpose of HTML helper of ActionLink in ASP.NET MVC?

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.


1 Answers

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.

like image 168
Selman Genç Avatar answered Oct 31 '22 10:10

Selman Genç