Reputation: 7909
I am trying to create a HtmlHelper
extension that would build a form
in the backend.
Something like this:
public static IHtmlContent HiddenFormFor<TModel, TResult>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
string buttonDescription)
{
var builder = new HtmlContentBuilder();
// This is the part that doesn't fit, I just copied how it's done in the view:
using(htmlHelper.BeginForm("index", "home"))
{
builder.AppendHtml(htmlHelper.HiddenFor(expression));
builder.AppendHtml($"<span type=\"submit\" class=\"label label-primary\">{htmlHelper.Raw(buttonDescription)}</span>");
}
return builder;
}
The problem with this is that I don't know how to get the elements built with BeginForm
and EndForm
and put them into the builder
.
Upvotes: 0
Views: 305
Reputation: 441
As i already suggested in the comments: Just use partial views
But as you still request to know how to use it in the backend. Seems like you should look into how Razor
works ;) With Razor
you are still calling methods from classes in namespaces. BeginForm
is a method from the FormExtensions
.
So you could do the following:
...
Using System.Web.Mvc.Html;
public static IHtmlContent HiddenFormFor<TModel, TResult>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
string buttonDescription)
{
var content = new StringBuilder();
content.Append(FormExtensions.BeginForm(htmlHelper)); //adding <form> to htmlhelper
content.append(htmlHelper.HiddenFor(expression)); //Add hidden value
content.append(FormExtensions.EndForm(htmlHelper)); //adding </form> to htmlHelper
return MvcHtmlString.Create(content.ToString());
}
EDIT Looking into it a bit more i found what i think should be the solution. Check the code above
Upvotes: 2