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;
}
现在我遇到了困难。如何让此删除按钮起作用?
答案 0 :(得分:4)
如果你想生成完整的代码,那么让它返回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("");
}
答案 1 :(得分:1)
虽然我认为<form>
元素可以解决问题,但它不是非常AJAX-y。
相反,为什么不使用jQuery,wire up to the click event来获取相应的<a>
链接,然后使用issue an HTTP POST to the server yourself?
$document.ready(function () {
// "deleteLink is a class that identifies links that
// are used for deleting, you might have some other mechanism
$("a .deleteLink").click(function () {
$.post('post url', function(data) {
// Do something with the data returned
});
});
});
这样做的好处是让你的HTML 更多更清洁,而不是为你要删除的每个项目插入<form>
,并且语义相关,干净的标记总是一个加号从开发,搜索引擎优化和其他角度来看。