.NET Tips and Tricks

Blog archive

Ensure HTML Forms Are Closed with the Using Block and BeginForm

In your Views, you can get the BeginForm helper to not only write out the open tag for your HTML form, but to write out your form's end tag. The trick is to call BeginForm as part of a Using block. The code looks like this, in Visual Basic:

@Using Html.BeginForm(...parms...)
  @Html.EditorFor(...
  ...rest of form...
End Using

This C# code does the same thing:

@using (Html.BeginForm(...parms...))
{
  @Html.EditorFor(...
  ...rest of form...
}

At the end of the Using block, the compiler will automatically call the Dispose method of the class the BeginForm uses. That Dispose method will politely add the end form tag to your page, so you'll end up with something like this:

<form action="...rest of the attributes...>
  <input type="text"...
  ...rest of form...
</form>

As you can see, the Using block also creates a structure in your View that you can slip all of your form elements inside.

Posted by Peter Vogel on 01/28/2016


comments powered by Disqus

Featured

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

  • Introduction to .NET Aspire

    Two Microsoft experts will present on the cloud-native application stack designed to simplify the development of distributed systems in .NET at the Visual Studio Live! developer conference coming to Las Vegas next month.

  • Microsoft Previews Copilot AI for Open-Source Eclipse IDE

    Catering to Java jockeys, Microsoft is yet again expanding the sprawling reach of its Copilot-branded AI assistants, previewing a coding tool for the open-source Eclipse IDE.

Subscribe on YouTube

Upcoming Training Events