Reputation: 43
I am writing some code where I would like render a MVC BeginForm but to also include additional HTML.
For eg.
@using (Html.BeginMyCustomForm()) {
}
And this spits out
<form action="" etc>
PLUS
<input type="hidden" name="my-additional-field-i-always-want">
@Html.ValidationMessageFor(m => m)
Is this possible?
I know I'll be looking at some kind of extension or something most likely.
Hope this makes sense and thanks in advance!
Upvotes: 4
Views: 142
Reputation: 93434
It's not a good idea to include such things in an extension to BeginForm. The reason is that good design dictates that objects should do one thing. This is called the Single Responsibility Principle.
You now want your form object to also create inputs and validation.
Instead, use the MVC templating system and create a default template to use for your needs. You should also use Html.HiddenFor rather than using an input tag, unless there is some specific reason not to.
Another option is to use MVC Scaffolding to generate what you want.
More about Editor Templates http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html
More about Scaffolding http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/
Upvotes: 2
Reputation: 636
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;
}
}
Upvotes: 1