使用HtmlHelper获取.cs.html页面属性



与主题一样,有没有办法在控制器中获取HTML标记的属性?

该问题涉及以下条款:https://www.itorian.com/2012/10/html-helper-for-image-htmlimage.html

(很抱歉我以前没有把链接放在这里,我只是觉得它很常用(

是否可以进行以下任何尝试?

  • 第一次尝试

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));
}
  • 第二次尝试

.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));
}

从javascript中获取值并通过参数发送。

要获得文档的高度,请使用Javascript或jQuery

请注意剃刀是一个模板引擎。它只是将html代码作为文本处理。您想要做的事情在客户端(客户端的浏览器(中看起来非常容易实现,因为有DOM对象。

我建议在razor中创建html标签(在服务器中(,并通过css文件添加样式(在浏览器中应用(,如果您需要一些更复杂的样式控制,请用JavaScript编写,以便在浏览器中使用该样式。

例如,使用jQuery,您可以用$(function() { /* set-up code */ })编写这样的设置脚本。请在此处查看其详细信息。

最新更新