MVC3 Html.BeginForm () with optional HTML

I am writing code in which I would like to display MVC BeginForm, but also include additional HTML.

For instance,

@using (Html.BeginMyCustomForm()) { } 

And it spits out

 <form action="" etc> 

a plus

 <input type="hidden" name="my-additional-field-i-always-want"> @Html.ValidationMessageFor(m => m) 

Is it possible?
I know that I will look at some kind of extension or something most likely.
Hope this makes sense and thanks in advance!

+4
source share
2 answers

Maybe you can use something like this?

 public static class FormExtensions { public static MvcForm BeginMyCustomForm(this HtmlHelper htmlHelper) { var form = htmlHelper.BeginForm(); htmlHelper.ViewContext.Writer.write( .... ) return form; } } 
+1
source

It is not recommended to include such things in the BeginForm extension. The reason is that good design dictates that objects must do one thing. This is called the principle of shared responsibility.

Now you want your form object to also create inputs and validate.

Instead, use the MVC template system and create a default template that will be used for your needs. You should also use Html.HiddenFor, and not use an input tag, unless there is a specific reason.

Another option is to use MVC Scaffolding to generate what you want.

More information on the editor templates http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html

Read more about scaffolding http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/

+2
source

Source: https://habr.com/ru/post/1436502/


All Articles