MVC make action link perform a submit
Asked Answered
O

8

7

I am currently trying to make an html submit occur, but using the MVC helper method ActionLink as I do not want it to be a button, I want it to be an underlined link like the rest on my page. This is what I have currently

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

This jumps back to my action fine, but all the domains that are checked off to be deleted are not sent back. (if I use this, <input type="submit" name="DeleteAction" value="Delete" /> it works fine so I know it's not something wrong with submitting or retrieving the check boxes)

Here's what I have so far ...

>" %>

Index

<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>**

Oligosaccharide answered 10/8, 2010 at 14:5 Comment(1)
I've written about this in my blog post ASP.NET MVC LinkButton with HtmlHelper extensions. PeteRematch
E
5

You cannot make a hyperlink submit a form without Javascript.

Using jQuery, you can write

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

$('.DeleteLink').click(function() { 
    $(this).closest('form')[0].submit();
});
Engrossment answered 10/8, 2010 at 14:10 Comment(9)
Where would I put the jQuery statements? Directly in the View or do I create a separate javascript file for it? Also, will this know what action to submit the form to? (Sorry I haven't worked much with jquery or javascript)Oligosaccharide
You can put it in a <script> tag in the view.Engrossment
$(this).closest('form') will find the innermost <form> tag that contains the clicked element. Therefore, it will submit the form containing the link.Engrossment
Well I have added these lines to my View, and when I click the link nothing happens. The a href link is inside of the form, and the function was places just before the closing </asp:Content> tag (putting it outside this tag caused an error) Any insite on why this may be? I am not using the <form> tag, but rather the Html.BeginForm (so that I can specify the controller and action the form should return to).Oligosaccharide
You probably put the script in the <head> tag, which causes it to execute before the page loads. Therefore, when the script runs, there aren't any .DeleteLink elements to add event handlers to. Wrap the code in $(function() { ... }) or move it below the forms.Engrossment
The Html.BeginForm method renders a normal <form> tag, so it doesn't matter.Engrossment
Including the <script> tag? sorry very new to this, and also it's not wrapped in anytag except the <asp:Content> tag because it is literally the last line before this ending tag occurs.Oligosaccharide
@DMan: No, only the code inside of it. If the <script> tag is already after the forms, it should already work. Can you show me the rendered source of your page on JSBin.com?Engrossment
how do I send that to you on there?Oligosaccharide
R
2

Adding to SLaks, you can ensure that your jQuery code fires at the appropriate time (regardless of location on the page) by using the following:

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

By wrapping the code in $(document).ready(...) you ensure that the code will not run before the page is finished loading.

Reasonless answered 11/8, 2010 at 16:17 Comment(0)
S
1

Instead of creating an action link, you are better off writing client-side javascript code which will submit the form for you when the link is clicked.

You can easily use jQuery to do this, using the submit method on a selector which selects the form:

<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>
Sangria answered 10/8, 2010 at 14:10 Comment(3)
Your formSelector is a jQuery object, not a selector. Selectors are strings such as #myForm or form:has(a.DeleteLink). Also, since the form submit will reload the page, there is no point in that variable in the first place.Engrossment
@SLaks: Yes, it's a jQuery object, but it's an object that represents the results of the selector, so it was more semantically correct IMO. I've changed it regardless. As for reloading the page, that's not true. If form submission fails (say you are using jQuery form validation) then the page will not always reload on click.Sangria
This method does not work either, it just puts a # at the end of my URLOligosaccharide
B
1

Most of the answers I saw rely on jQuery or do some fancy ajax submit, which is not what I wanted. So I wrote HtmlHelper extension method that creates plain form with hidden inputs and buttons. It's work in progress... still can do the job. Here is class:

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

To use it, in Razor you write:

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

And as result, in HTML you get:

<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>
Briefs answered 19/3, 2015 at 21:54 Comment(0)
M
0

if you are using bootstrap, to make a button look like a link just add the btn-link class, for example

<input type="submit" name="ActionType" value="Edit" class="col-md-1 btn btn-link" />
Mccay answered 24/7, 2015 at 10:53 Comment(0)
T
0

This can be done by calling class from javascript in C#

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

For Razor Syntax

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

Then call Jquery to do submit.

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

Update 1# Little explanation where we can use this.

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

Going to Original question MVC make action link perform a submit
Index.cshtml example chtml View file

@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>
Twyla answered 22/6, 2016 at 20:24 Comment(1)
You should really add some explanation as to why this code should work - you can also add comments in the code itself - in its current form, it does not provide any explanation which can help the rest of the community to understand what you did to solve/answer the question.Cheapjack
A
0

I attempted Summit's approach above in Razor but needed to make some changes. Including the Controller's name in the action link caused the page to bypass the JQuery and directly submit the form. So, I tried the following:

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

From there I was able to access the button by id and use the onclick method.

$("#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;

 });

I should add that I wanted the form to be submitted but didn't necessarily want to be transferred to another page and/or Action.

Anadiplosis answered 13/4, 2017 at 17:10 Comment(0)
B
0

i did it in other way i put the link inside form tag and submit the form by the the link

<form  id="formid" action=  >  http="javascript:document.getElementById("formId".submit()"
</form>
Blaise answered 19/4, 2019 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.