Se si desidera generare il codice completo, si sta sbagliando erroneamente di restituire uno MvcForm
. Si desidera che restituisca un MvcHtmlString
e costruisca l'HTML all'interno del metodo. In questo modo è possibile utilizzarlo come:
@Html.DeleteButton("Delete", "Boodschap", new { id = item.BoodschapID });
Generazione direttamente il codice HTML (nota: non testato, potrebbe essere necessario adeguati controlli nulli, ecc)
public static MvcHtmlString DeleteButton(this HtmlHelper helper, string name,
string actionName, object htmlAttributes)
{
return DeleteButton(helper, name, actionName, null, null, htmlAttributes);
}
public static MvcHtmlString DeleteButton(this HtmlHelper helper, string name,
string actionName, string controllerName, object routeValues,
object htmlAttributes)
{
var buttonBuilder = new TagBuilder("button");
buttonBuilder.SetInnerText(name);
var formBuilder = new TagBuilder("form");
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
formBuilder.Attributes.Add("action", urlHelper.Action(
actionName, controllerName, routeValues))
formBuilder.Attributes.Add("method", FormMethod.Post);
formBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
formBuilder.InnerHtml = buttonBuilder.ToString();
return new MvcHtmlString(formBuilder.ToString());
}
Un'alternativa sarebbe quella di riutilizzare le helper delle form e Response.Write, ma hanno il metodo restituisce una stringa (vuoto), forse qualcosa di simile:
public static MvcHtmlString DeleteButton(this HtmlHelper helper, string name, string actionName, object routeValues)
{
return DeleteButton(helper, name, actionName, null, routeValues, null);
}
public static MvcHtmlString DeleteButton(this HtmlHelper helper, string name, string actionName, string controllerName, object routeValues, object htmlAttributes)
{
using (helper.BeginForm(actionName, controllerName, routeValues, FormMethod.Post, htmlAttributes))
{
var response = helper.ViewContext.HttpContext.Response;
var builder = new TagBuilder("button");
builder.SetInnerText(name);
response.Write(builder.ToString(TagRenderMode.Normal));
}
return MvcHtmlString.Create("");
}
Ho modificato l'ultima risposta che, dopo alcune modifiche, sembra funzionare correttamente. –
Informazioni dettagliate su come eseguire 'response.Write' in HtmlHelper. Grazie!! Vorrei poter votare di nuovo. –