注意:我最初发布了一个类似于here的问题,但我决定重新发布,因为我克服了原始问题并在此过程中修改了设计。我认为这是一个新话题,因为随着设计的改变,问题也从根本上改变了。我只想说清楚,我并没有试图用同样的问题来解决这个问题。
问题:我一直在做一些小经验,看看我是否可以创建一个帮助方法来将我的任何类型序列化为我指定的任何类型的HTML标记。我想我会把它放到社区,以帮助我识别代码气味或设计中的其他缺陷/效率低下,以改善设计。
基本上,我有这个代码会产生一个选择框(或任何其他Html元素),其中包含许多选项:
// the idea is I can use one method to create any complete tag of any type
// and put whatever I want in the content area.
// This makes the generation of all html completely testable
<% using (Html.GenerateTag<SelectTag>(Model, new { href = Url.Action("ActionName") })) { %>
// model is type ShareClass. It contains a list of Funds
<%foreach (var fund in Model.Funds) {%>
<% using (Html.GenerateTag<OptionTag>(fund)) { %>
<%= fund.Name %>
<% } %>
<% } %>
<% } %>
将生成以下html输出:
<select shareclassname="MyShareClass"
shareclasstype="ShareClass_A"
href="/Ctrlr/ActionName">
<option selected="selected" id="1" name="MyFund_1">MyFund_1</option>
<option id="2" name="MyFund_2">MyFund_2</option>
<option id="3" name="MyFund_3">MyFund_3</option>
<option id="N" name="MyFund_N">MyFund_N</option>
</select>
此Html.GenerateTag助手定义为:
public static MMTag GenerateTag<T>(this HtmlHelper htmlHelper, object elementData, object attributes) where T : MMTag
{
return (T)Activator.CreateInstance(typeof(T), htmlHelper.ViewContext, elementData, attributes);
}
根据T的类型,它将创建以下定义的类型之一:
public abstract class HtmlTypeBase : MMTag
{
public HtmlTypeBase(ViewContext viewContext, params object[] elementData)
{
_tag = this.GetTag();
base._viewContext = viewContext;
base.MergeDataToTag(viewContext, elementData);
}
public abstract TagBuilder GetTag();
}
public class SelectTag : HtmlTypeBase
{
public SelectTag(ViewContext viewContext, params object[] elementData)
: base(viewContext, elementData)
{
base._tag = new TagBuilder("select");
}
public override TagBuilder GetTag()
{
return new TagBuilder("select");
}
}
public class OptionTag : HtmlTypeBase
{
public OptionTag(ViewContext viewContext, params object[] elementData)
: base(viewContext, elementData)
{
base._tag = new TagBuilder("option");
}
public override TagBuilder GetTag()
{
return new TagBuilder("option");
}
}
public class AnchorTag : HtmlTypeBase
{
public AnchorTag(ViewContext viewContext, params object[] elementData)
: base(viewContext, elementData)
{
base._tag = new TagBuilder("a");
}
public override TagBuilder GetTag()
{
return new TagBuilder("a");
}
}
这是MMTag的定义:
public class MMTag : IDisposable
{
internal bool _disposed;
internal ViewContext _viewContext;
internal TextWriter _writer;
internal TagBuilder _tag;
public MMTag() {}
public MMTag(ViewContext viewContext, params object[] elementData){ }
protected void MergeDataToTag(ViewContext viewContext, object[] elementData)
{
MergeTypeDataToTag(elementData[0]);
MergeAttributeDataToTag(elementData[1]);
this._viewContext = viewContext;
this._viewContext.Writer.Write(_tag.ToString(TagRenderMode.StartTag));
}
private void MergeAttributeDataToTag(object attributeData)
{
var dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
var attributes = attributeData;
if (attributes != null)
{
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(attributes))
{
object value = descriptor.GetValue(attributes);
dic.Add(descriptor.Name, value);
}
}
_tag.MergeAttributes<string, object>(dic);
}
private void MergeTypeDataToTag(object typeData)
{
Type elementDataType = typeData.GetType();
foreach (PropertyInfo prop in elementDataType.GetProperties())
{
if (prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(Decimal) || prop.PropertyType == typeof(String))
{
object propValue = prop.GetValue(typeData, null);
string stringValue = propValue != null ? propValue.ToString() : String.Empty;
_tag.Attributes.Add(prop.Name, stringValue);
}
}
}
#region IDisposable
public void Dispose()
{
Dispose(true /* disposing */);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing)
{
_writer = _viewContext.Writer;
_writer.Write(_tag.ToString(TagRenderMode.EndTag));
}
}
}
#endregion
}
我还应该补充一下该基金&amp; ShareClass定义为:
public class Fund
{
public int ID { get; set; }
public string Name { get; set; }
public Fund()
{
this.ID = 123;
this.Name = "MyFund";
}
public Fund(int id, string name)
{
this.ID = id;
this.Name = name;
}
}
public class ShareClass
{
public string ShareClassName { get; set; }
public string ShareClassType { get; set; }
public IEnumerable<Fund> Funds { get; set; }
public ShareClass(string name, string shareClassType)
{
this.ShareClassName = name;
this.ShareClassType = shareClassType;
}
}
答案 0 :(得分:1)
您是否考虑过使用约定来创建代码?看起来您在视图中需要大量重复的代码。每次你想要下拉时你都需要复制六行。
使用固定意见的输入构建器可以大大简化您的视图,但需要您进行一些设置。根据我的经验,这个设置非常值得您节省下来的时间!
输入构建器的想法是指定视图模型上的属性有输入元素(或显示或标签等)。然后,您的输入构建器框架会检查属性的类型和属性,并确定要呈现的正确输入类型。
以下是我当前项目中如何构建下拉列表的示例:
//View Model
[OptionsFrom("Years")]
public int ContractYear{ get; set; }
public IDictionary Years
{
get
{
var currentYear = DateTime.Today.Year;
return Enumerable.Range(0, 10).ToDictionary(i => currentYear + i, i => (currentYear + i).ToString());
}
}
//View
Html.InputFor(x => x.ContractYear);
Here是使用MVCContrib输入构建器的演练。我知道在MVC2中也有一些输入构建器支持,但我不熟悉它。在我看来,最好的基于会议的建设者可以从FubuMVC获得。我有一篇关于如何在ASP.NET MVC中使用它们的帖子here。我还没有关于如何配置它们的任何帖子,尽管我很快就会计划。