【问题标题】:MVC make action link perform a submitMVC 使动作链接执行提交
【发布时间】:2010-08-10 14:05:44
【问题描述】:

我目前正在尝试进行 html 提交,但使用 MVC 辅助方法 ActionLink 因为我不希望它是一个按钮,我希望它是一个带下划线的链接,就像我页面上的其余部分一样。这是我目前拥有的

<%= Html.ActionLink("Delete Selected", "DeleteCheckBox", "Domains", "Default.aspx", new { type="submit" }) %>

这很好地跳回到我的操作,但是所有被选中要删除的域都不会被发回。 (如果我使用它,&lt;input type="submit" name="DeleteAction" value="Delete" /&gt; 它工作正常,所以我知道提交或检索复选框没有问题)

这是我目前所拥有的......

>" %>

指数

<h2>Domain List</h2>

<h2 style="color: #FF0000"><%= Html.Encode(ViewData[IProwlAdminUI.Utils.Global.ExceptionMessageKey]) %></h2>
<h2 style="color: #FF0000"><%= Html.Encode(ViewData["Message"]) %></h2>

<% using (Html.BeginForm("DeleteCheckBox", "Domains"))
   { %>
   <% if (ViewData.ContainsKey("DeleteMessage")) 
       { %>
       <h2 style="color: #FF0000"><%= Html.Encode(ViewData["DeleteMessage"]) %></h2>
       <input type="submit" name="DeleteAction" value="Commit" /> <input type="reset" name="DeleteAction" value="Cancel" /> 
    <% } %>
   <p>
    <%= Html.ActionLink("Create New", "Create") %> 
    | <%= Html.ActionLink("Export List", "Export") %> 
    | **<a href="javascript:void(0)" class="DeleteLink">Delete Selected</a>**

    <% if (ViewData.ContainsKey("Path")) 
       { %> 
       | <%= Html.ReferenceToFile("/download/Domains.xls", "Exported File") %>
    <% } %>
    </p>

    <div style="overflow:scroll; width:100%">
    <% Html.Telerik().Grid(Model).Name("Domains")
        .DataKeys(dataKeys => dataKeys.Add(c => c.DomainId)).DataKeys(dataKeys => dataKeys.Add(c => c.Name))
        .Columns(columns =>
        {
            columns.Template(o =>
            {  %>
                <%= Html.ActionLink("Edit", "Edit", new { id = o.DomainId })%> 
                <%
        }).Title("Edit");
            columns.Template(o =>
            { %>
            <% if (ViewData.ContainsKey("DeleteMessage"))
               { %>
               <input type='checkbox' checked="checked" id='<%= o.Name %>' name='DeleteIds' value='<%= o.DomainId %>' />
            <% } %>
            <% else
                { %>
               <input type='checkbox' id='<%= o.Name %>' name='DeleteIds' value='<%= o.DomainId %>' />
             <% } %>
               <%
        }).Title("Delete");

            columns.Bound(o => o.DomainId);
            columns.Bound(o => o.Name);
            columns.Bound(o => o.SiteId);
            columns.Bound(o => o.ScrubAndRedirect);
            columns.Bound(o => o.ReportingSiteId);
            columns.Bound(o => o.TrafficCopClass);
            columns.Bound(o => o.SiteName);
            columns.Bound(o => o.FeedType);
            columns.Bound(o => o.Active);
        }).Sortable().Filterable().DataBinding(db => db.Server().Select("Index", "Domains")).Render();%>
     </div> 
     <% if (!ViewData.ContainsKey("DeleteMessage"))
        { %>
     <input type="submit" name="DeleteAction" value="Delete" />   
     <% } %>
<% } %>     
<p>
    <%= Html.ActionLink("Create New", "Create") %> | <%= Html.ActionLink("Export List", "Export") %> 
    <% if (ViewData.ContainsKey("Path")) 
       { %> 
       | <%= Html.ReferenceToFile("/download/Domains.xls", "Exported File") %>
    <% } %>
</p>
**<script type="text/javascript">
    $(function() {
        $('.DeleteLink').click(function() {
            $(this).closest('form')[0].submit();
        });
    });
</script>**

【问题讨论】:

标签: c# asp.net-mvc actionlink


【解决方案1】:

您不能在没有 Javascript 的情况下通过超链接提交表单。

使用jQuery,你可以写

<a href="javascript:void(0)" class="DeleteLink">Delete Selected</a>

$('.DeleteLink').click(function() { 
    $(this).closest('form')[0].submit();
});

【讨论】:

  • 我应该把 jQuery 语句放在哪里?直接在视图中还是我为它创建一个单独的 javascript 文件?另外,这会知道将表单提交到什么操作吗? (对不起,我没有太多使用 jquery 或 javascript)
  • 你可以把它放在视图中的&lt;script&gt;标签中。
  • $(this).closest('form') 将找到包含被点击元素的最里面的&lt;form&gt; 标签。因此,它将提交包含链接的表单。
  • 好吧,我已将这些行添加到我的视图中,当我单击链接时没有任何反应。 a href 链接位于表单内部,并且该函数位于结束 标记之前(将其放在此标记之外会导致错误)任何关于为什么会这样的网站?我没有使用
    标记,而是使用 Html.BeginForm(以便我可以指定表单应返回的控制器和操作)。
  • 您可能将脚本放在&lt;head&gt; 标记中,这会导致它在页面加载之前执行。因此,当脚本运行时,没有任何.DeleteLink 元素可以添加事件处理程序。将代码包装在$(function() { ... }) 中或将其移至表单下方。
【解决方案2】:

添加到 SLaks,您可以使用以下方法确保您的 jQuery 代码在适当的时间(无论页面上的位置)触发:

<script type="text/javascript">
   $(document).ready(function(){
      $('.DeleteLink').click(function() { 
         $(this).closest('form')[0].submit();
       });
   });
</script>

通过将代码包装在$(document).ready(...) 中,您可以确保代码在页面加载完成之前不会运行。

【讨论】:

    【解决方案3】:

    您最好编写客户端 javascript 代码,而不是创建操作链接,该代码将在单击链接时为您提交表单。

    您可以轻松地使用jQuery 来执行此操作,在选择表单的选择器上使用submit method

    <form id="myForm">
       <!-- Other form inputs -->
       <a id="myFormSubmit" href="#">Submit form</a>
    </form>
    
    <script>
        // Assuming you have jQuery loaded.
        $(document).ready(function() {
            // Can load the results of the selector 
            // for the form here.
            // No need to load it every time in the
            // event handler.
            // Even though more often than not the
            // form will cause a reload of the page
            // if you are using the jQuery form validation
            // plugin, you could end up calling the click
            // event repeatedly.
            var myForm = $("#myForm");
    
            // Add the event handler for the link.
            $("#myFormSubmit").click(function() {
                // Submit the form.
                myForm.submit();
    
                // Return false, don't want
                // default click action to take place.
                return false;
            });
        });
    
    </script>
    

    【讨论】:

    • 您的 formSelector 是一个 jQuery 对象,而不是一个选择器。选择器是字符串,例如 #myFormform:has(a.DeleteLink)。此外,由于表单提交将重新加载页面,因此该变量首先没有意义。
    • @SLaks:是的,它是一个 jQuery 对象,但它是一个表示选择器结果的对象,因此它在 IMO 语义上更正确。我已经改变了它。至于重新加载页面,那不是真的。如果表单提交失败(假设您正在使用 jQuery 表单验证),那么页面将总是在点击时重新加载。
    • 这个方法也不起作用,它只是在我的网址末尾放了一个#
    【解决方案4】:

    我看到的大多数答案都依赖于 jQuery 或者做一些花哨的 ajax 提交,这不是我想要的。所以我编写了 HtmlHelper 扩展方法,该方法创建带有隐藏输入和按钮的普通表单。它正在进行中......仍然可以完成这项工作。这里是类:

    public static class HtmlHelperExt
    {
        public static HtmlString PostLink(this HtmlHelper html, string text, string action, object routeValues)
        {
            var tbForm = new TagBuilder("form");
            tbForm.MergeAttribute("method", "POST");
            tbForm.MergeAttribute("action", action);
    
            var inputDict = HtmlHelper.ObjectToDictionary(routeValues);
            var inputs = new List<string>();
            foreach (var key in inputDict.Keys)
            {
                const string inputFormat = @"<input type='hidden' name='{0}' value='{1}' />";
    
                var input = String.Format(inputFormat, key, html.Encode(inputDict[key]));
                inputs.Add(input);
            }
    
            var submitBtn = "<input type='submit' value='{0}'>";
            inputs.Add(String.Format(submitBtn, text));
    
            var innerHtml = String.Join("\n", inputs.ToArray());
            tbForm.InnerHtml = innerHtml;
    
            // return self closing
            return new MvcHtmlString(tbForm.ToString());
        }
    }
    

    要使用它,请在 Razor 中编写:

    @Html.PostLink("ButtonText", "/Controller/Action", new { id = item.Id, hello="world" })
    

    结果,在 HTML 中你会得到:

    <form action="/Controller/Action" method="POST">
        <input type="hidden" name="id" value="1">
        <input type="hidden" name="hello" value="world">
        <input type="submit" value="ButtonText">
    </form>
    

    【讨论】:

      【解决方案5】:

      如果您使用引导程序,要使按钮看起来像一个链接,只需添加 btn-link 类,例如

      <input type="submit" name="ActionType" value="Edit" class="col-md-1 btn btn-link" />
      

      【讨论】:

        【解决方案6】:

        这可以通过在 C# 中从 javascript 调用类来完成

         <%= Html.ActionLink("Delete Selected", "DeleteCheckBox", "Domains", "Default.aspx", new { class= "dosubmit" }) %>
        

        对于 Razor 语法

        @Html.ActionLink("Delete Selected", "Index", "IndexController", "null", new { @class= "dosubmit" })
        

        然后调用 Jquery 进行提交。

        <script type="text/javascript">
        $(function() {
            $('dosubmit').click(function(e) {
                e.preventDefault();
                $(this).parents('form').first().submit();
            });
        });
        </script>
        

        更新1# 很少解释我们可以在哪里使用它。

        <input type="submit" name="dosubmit" value="Submit something" />
        

        转到原始问题MVC 使操作链接执行提交
        index.cshtml 示例 chtml 查看文件

        @using(Html.BeginForm("Index","ControllerName",FormMethod.Post))
        {
           //  Call another view  <a></a> with bootstrap button class
            @Html.ActionLink("Submit something", "Index", "IndexController", "null", new { @class= "dosubmit btn btn-success"  })
        }
        // Perform a post submit method with same button
        <script type="text/javascript">
        $(function() {
            $('dosubmit').click(function(e) {
                e.preventDefault();
                $(this).parents('form').first().submit();
            });
        });
        </script>
        

        【讨论】:

        • 你真的应该添加一些解释为什么这个代码应该工作 - 你也可以在代码本身中添加 cmets - 在它的当前形式中,它没有提供任何可以帮助其余部分的解释社区了解您为解决/回答问题所做的工作。
        【解决方案7】:

        我在 Razor 中尝试了上述 Summit 的方法,但需要进行一些更改。在 action 链接中包含 Controller 的名称会导致页面绕过 JQuery 并直接提交表单。所以,我尝试了以下方法:

        @using (Html.BeginForm())...
        @Html.ActionLink("ButtonText", "Action", null, null, new { @id = "ButtonID", 
        @class = "btn btn-primary btn-sm" })
        

        从那里我可以通过 id 访问按钮并使用 onclick 方法。

        $("#ButtonID").on("click", function (e) {
            url = $(this).attr('href'); // without Action in link url shows as 
                                       // /Controller
            e.preventDefault(); // use this or return false
        
            // now we can do an Ajax submit;
        
         });
        

        我应该补充一点,我希望提交表单,但不一定希望转移到另一个页面和/或操作。

        【讨论】:

          【解决方案8】:

          我以其他方式做到了 我把链接放在表单标签里面 并通过链接提交表单

          <form  id="formid" action=  >  http="javascript:document.getElementById("formId".submit()"
          </form>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-09-25
            • 1970-01-01
            • 2011-12-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多