Trivial implementation of File uploader

Hello everybody,

today I want to share with you fragment of code of html extension.

Imagine that you edit your cshtml file, and see following code:

@Html.EditorFor(model => model.SomeField

Then you need to add some file upload and notice, that there is not file upload! 

How can you fix this situation?

I propose to use HtmlExtension code. For example like this:

 public static MvcHtmlString FileUpload(this HtmlHelper htmlHelper, string cssClass, object htmlAttrs = null) {
  var tb = new TagBuilder("input");
  tb.MergeAttribute("type", "file");
  if (!string.IsNullOrWhiteSpace(cssClass)) {

  return MvcHtmlString.Create(tb.ToString(TagRenderMode.SelfClosing));

Then in your .cshtml file you will be able to write the following:

@Html.FileUpload("form-control filestyle", new { data_classbutton = "btn btn-default", data_classinput = "form-control inline" })

Take note that data_classbutton will be transformed by TagBuilder into data-classbutton. That is some kind of convention over configuration.

No Comments

Add a Comment