在mvc razor视图中渲染简单的输入元素

时间:2016-04-13 13:55:36

标签: c# .net asp.net-mvc razor

让我们说我有以下html适用于我的表格

<input 
      data-msg-date="The field RequiredDateDemo must be a date." 
      data-msg-required="The RequiredDateDemo field is required." 
      data-rule-date="true" 
      data-rule-required="true" 
      id="RequiredDateDemo" name="RequiredDateDemo" type="text" value="" />

如果我有像

这样的模特
public class MyModel{
     [Required]
     public DateTime RequiredDateDemo { get; set; }
}
  

如何使用mvc中的html助手生成上面的html代码   剃刀观点?

2 个答案:

答案 0 :(得分:1)

namespace CustomHelpers
{
  public static class HtmlHelperExtensions
  {
    public static MvcHtmlString CustomTextBox(this HtmlHelper htmlHelper, string name, string value)
    {
      var builder = new TagBuilder("input");
      builder.MergeAttribute("type", "text");
      builder.MergeAttribute("name", name);
      builder.MergeAttribute("value", value);
      return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
    }
  }
}

http://dotnet-helpers.com/2013/08/05/how-to-create-custom-html-helpers-using-mvc-4-razor/

答案 1 :(得分:1)

如果您只想从.cshtml页面进行操作,那么您可以按照以下方式进行:

Column