Shawn Mclean
Shawn Mclean

Reputation: 57469

ASP.NET MVC html helper code used to convert model to PropertyName

This code:

@Html.HiddenFor(model => model.Country.CountryId)

gives this output:

<input type="hidden" id="Country_CountryId" name="Country.CountryId" />

Is there a way to get the id of the above code by using just the model? For eg.

@Html.TestBoxFor(model => model.Country.CountryName, new { data_HiddenId= model.Country.CountryId.GetHtmlRenderOrSomething())

which should give this:

<input type="text" id="Country_CountryName" name="Country.CountryName" data-HiddenId="Country_CountryId" />

My main concern is data-HiddenId. I want it to be equal to the id generated for the hidden input above.

Upvotes: 1

Views: 1598

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

You could try this:

@Html.TestBoxFor(
    model => model.Country.CountryName, 
    new { 
        data_hiddenid = ExpressionHelper.GetExpressionText((Expression<Func<ModelType, int>>)(x => x.Country.CountryId))
    }
)

and to reduce the ugliness you could write a custom HTML helper:

public static class HtmlExtensions
{
    public static MvcHtmlString TextBoxWithIdFor<TModel, TProperty, TId>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TProperty>> expression, 
        Expression<Func<TModel, TId>> idExpression
    )
    {
        var id = ExpressionHelper.GetExpressionText(idExpression);
        return htmlHelper.TextBoxFor(expression, new { data_hiddenid = id });
    }
}

and then simply:

@Html.TestBoxWithIdFor(
    model => model.Country.CountryName, 
    model => model.Country.CountryId
) 

Upvotes: 2

Related Questions