编程语言
首页 > 编程语言> > c# – 创建MVC删除按钮扩展 – 如何扩展MVC的Html助手?

c# – 创建MVC删除按钮扩展 – 如何扩展MVC的Html助手?

作者:互联网

ASP.NET MVC 2呈现删除记录的链接(即< a>).

允许通过GET操作执行删除操作可能是有害的,因此我想通过发出POST来执行删除操作.

我创建了以下代码:

<% using (Html.BeginForm("Delete", "Boodschap", new { id = item.BoodschapID }))
    { %>
    <button>Delete</button>
<% } %>

现在我想将此代码添加到Html助手中作为扩展方法:

public static MvcForm DeleteButton(this HtmlHelper helper, string name, 
    string actionName, string controllerName, string routeValues)
{
    MvcForm form = helper.BeginForm(actionName, controllerName, routeValues);
    return form;
}

现在这里是我被卡住的地方.如何让此删除按钮起作用?

解决方法:

如果你想生成完整的代码,那么让它返回一个MvcForm是错误的.您希望让它返回MvcHtmlString并在方法中构造HTML.这样你就可以用它:

@Html.DeleteButton( "Delete", "Boodschap", new { id = item.BoodschapID } );

直接生成HTML(注意:未经测试,您可能需要适当的空值检查等)

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() );
}

另一种方法是重用表单助手和Response.Write,但让方法返回一个(空)字符串,可能是这样的:

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("");
}

标签:c,asp-net-mvc,html-helper,asp-net-mvc-2
来源: https://codeday.me/bug/20190521/1147221.html