0

As in the topic, is there any way to get HTML tags' attributes in the controller?

The question refers to the following article: https://www.itorian.com/2012/10/html-helper-for-image-htmlimage.html

(I'm sorry I didn't put the link here before, I just thought it's commonly used)

Is any of the following attempts possible?

  • First attempt

public static MvcHtmlString Image(this HtmlHelper helper, string src, string altText, string height = "")
{
    var builder = new TagBuilder("img");
    height != "" ? builder.MergeAttribute("height", height) : 
    // is there a way to get the size of the <html> tag?
    (helper.ViewDataContainer as WebViewPage).Height;
    return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
}
  • Second attempt

.cshtml file:
@{
    Dictionary<string, string> attributes = new Dictionary<string, string>();
    attributes.Add("height", // is it possible to get the height here?
    Html.Image("...", "...", attributes);
}

c# file:
public static MvcHtmlString Image(this HtmlHelper helper, string src, string altText, Dictionary<string, string> attributes)
{
    var builder = new TagBuilder("img");
    builder.MergeAttribute("src", src);
    builder.MergeAttribute("alt", altText);
    foreach (var element in attributes)
        builder.MergeAttribute(element.Key, element.Value);
    return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
}
  • better to use client side script to achieve this 'document.getElementById('myImg').setAttribute('height', document.documentElement.scrollHeight);` tag height can be determined on client side – Ppp Jul 19 '18 at 04:50

2 Answers2

0

Get your value from javascript and send in via parameter.

To get a height of your document use a Javascript or jQuery

Maciej Pulikowski
  • 2,457
  • 3
  • 15
  • 34
0

Be aware that razor is an template engine. It just handles html code as text. What you want to do looks really much easy to achieve in client side (client's browser) because there's DOM objects.

I recommend to create html tags in razor (in server), and add styles by css file (applied in browser), and if you need some more complex style control, write it in JavaScript so that the style is applied in browser.

For example, using jQuery, you can script such set-up with $(function() { /* set-up code */ }). see its details here.

Yas Ikeda
  • 973
  • 1
  • 9
  • 16