mvc htmlhelper扩展

 

public static MvcHtmlString NewTextBox(this HtmlHelper htmlHelper, string name, string value)
{
    var builder = new TagBuilder("input");
    builder.Attributes["type"] = "text";
    builder.Attributes["name"] = name;
    builder.Attributes["value"] = value;
    return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
}

public static MvcHtmlString NewTextBoxFor<TModel, TProperty>
(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
    var name = ExpressionHelper.GetExpressionText(expression);
    var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    return NewTextBox(htmlHelper, name, metadata.Model as string);
}
使用:
@Html.NewTextBoxFor(model => model.Title)
生成的代码如下:
<input name="Title" type="text" value="" />
将文本内容下载:
 public FileStreamResult CreateFile()
        {
            //todo: add some data from your database into that string:
            var string_with_your_data = "1234";

            var byteArray = Encoding.ASCII.GetBytes(string_with_your_data);
            var stream = new MemoryStream(byteArray);

            return File(stream, "application/pdf", "your_file_name.txt");
        }

view使用方法:

@Html.ActionLink("Download Text File", "CreateFile", "SomeController ")

posted on 2013-06-12 01:47  快乐于行  阅读(373)  评论(0编辑  收藏  举报