ASP.NET MVC - Adding "data-" attributes in Html.BeginForm()

When working with a data capture form in ASP.NET MVC Imagine this situation.

  • You need to use Knockout (or something else) for data binding (and other magic).
  • You need to use @using (Html.BeginForm()){} 
So the goal is to get this markup rendering in the browser using Html.BeginForm(method with the "data-" tags.

<form action="/invoices/upload" data-bind="submit: saveData" enctype="multipart/form-data" id="invoiceUploadForm" method="post">

For that the server side markup should be something like any of these.

  • Using a dictionary

@using (Html.BeginForm("Upload", "Invoices", FormMethod.Post, 
                        new Dictionary<string, object> { 
                            { "enctype", "multipart/form-data" }, 
                            { "data-bind", "submit: saveData"}, 
                            { "id", "invoiceUploadForm"} 
                        }))
{
   <!-- HTML -->
} 

  • Trick here is to use the underscore ( _ ) so that it will get rendered as a hyphen ( - ) in the browser

@using (Html.BeginForm("Upload", "Invoices", FormMethod.Post, 
                        new { 
                               enctype = "multipart/form-data", 
                               data_bind = "submit: saveData",
                               id = "invoiceUploadForm" 
                            }))
{
   <!-- HTML -->
} 

Popular posts from this blog

Print a receipt using a Thermal Printer with C#.NET

Automatic redirect upon session timeout using ASP.NET MVC and Javascript

Complex Master-Detail Form using Knockout.js and ASP.NET MVC