javascript razor 中 Url.Action 的确认

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17549550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:43:47  来源:igfitidea点击:

Confirmation for Url.Action in razor

javascriptasp.net-mvcrazor

提问by TBA

Hi I am using an edit button inside a gridview. I want a confirmation button before calling to the action?

嗨,我在 gridview 中使用编辑按钮。在调用操作之前我需要一个确认按钮吗?

grid.Column("","",format:@<text>@if(!item.IsBookPublished)
{
 <text> <a href='@Url.Action("EditBookByID","Books", new {BookID = @item.BookDetailsID, CreatedBy = @item.UserID , onclick = "return confirm('Are you sure you want to Edit?')" })'>Edit</a></text>
 }
 </text>

However the onclick property is not evaluating, instead it is passing as a parameter. How can I achieve confirmation?

但是 onclick 属性没有评估,而是作为参数传递。我怎样才能获得确认?

回答by Darin Dimitrov

You've placed it at the wrong place. Right now you've passed it as parameter to the Url.Action helper, whereas it should be a separate attribute, the same way you defined the href attribute:

你把它放在错误的地方。现在您已经将它作为参数传递给 Url.Action 助手,而它应该是一个单独的属性,与您定义 href 属性的方式相同:

<a href="@Url.Action("EditBookByID", "Books", new { bookID = item.BookDetailsID, CreatedBy = item.UserID })" onclick="return confirm('Are you sure you want to Edit?')">Edit</a>

By the way you should consider using helpers for that:

顺便说一句,您应该考虑为此使用助手:

grid.Column("", "", format:
    @<text>
        @if(!item.IsBookPublished)
        {
            Html.ActionLink(
                "Edit", 
                "EditBookByID", 
                "Books",
                new { bookID = @item.BookDetailsID },
                new { onclick = "return confirm('Are you sure you want to Edit?')" }
            )
        }
    </text>
)

回答by Ryan Weir

By putting the 'onclick' inside the Url.Action helper, you're tellingit to translate it as a URL parameter.

通过将 'onclick' 放在 Url.Action 助手中,您是在告诉它把它翻译成一个 URL 参数。

What you want to do instead is put the onclick outside the helper like this:

您想要做的是将 onclick 放在助手之外,如下所示:

<a href='@Url.Action("EditBookByID","Books", new {BookID = @item.BookDetailsID, CreatedBy = @item.UserID  })' onclick = "return confirm('Are you sure you want to Edit?')">
    Edit
<a>