【发布时间】:2014-03-09 13:08:56
【问题描述】:
在使用 WebForms 多年后,我最近开始向 MVC 过渡。我正在尝试创建一个可插入的轻量级内容编辑模块,但遇到了一些问题。
这个想法很简单:创建一个名为 EditableSimpleHtml 的 HtmlHelper,可以在 @using... { } 语法中使用,以便在剃刀视图中实现以下目标:
@using (Html.EditableSimpleHtml("MyKey"))
{
<h3>Test</h3>
<p>
1<br />
</p>
}
{...} 之间的值是在数据存储中找不到内容时的默认值。
我创建了一个 HtmlHelper。以下是简化版:
public static IDisposable EditableSimpleHtml(this HtmlHelper helper, string key)
{
// Get the content from the data storage using the key (I will not show the provider itself, its just a provider that will access a db)
var provider = ContentEditing.Provider;
string value = provider.GetValue(key);
if (value == null)
{
// No value found in the data storage for the supplied key, we have to use the default value from within the @using... { } statement
// Can I get that value here? I want to to store it initialy in the data storage
value = "..."; // How to get html from within the @using... { }?
}
return new ContentEditableHtmlString(helper, value);
}
public class ContentEditableHtmlString : IDisposable
{
private readonly HtmlHelper _helper;
public ContentEditableHtmlString(HtmlHelper helper, string value)
{
_helper = helper;
var builder = new TagBuilder("div");
var writer = _helper.ViewContext.Writer;
writer.Write(builder.ToString(TagRenderMode.StartTag));
writer.Write(value);
}
public void Dispose()
{
_helper.ViewContext.Writer.Write("</div>");
}
}
问题是我无法从 HtmlHelper 中的 @using... { } 语句中获取(默认)内容,或者至少我不知道如何获取。我需要它以防我最初想将它存储到数据库中。
第二个问题是@using... { } 语句之间的值总是会被渲染。在可以从数据存储中加载内容的情况下,我希望将默认值替换为数据存储中的值。
有没有办法实现这一点,还是我一开始就走错了路?
【问题讨论】:
-
找到一篇博文,概述了如何制作 Html.BeginForm() 之类的助手:scatteredcode.wordpress.com/2012/01/22/…
-
@MichaelDunlap 感谢您的建议,但问题不在于我不知道如何创建一个可以像 Html.BeginForm() 一样使用的助手。这实际上很容易。但更多的是我想使用/实现它的方式,正如我在我的 2 个主要问题中所描述的那样。
标签: asp.net-mvc razor html-helper asp.net-mvc-5