sagesky36
sagesky36

Reputation: 4692

Getting the name of a submit button

I'm using MVC 4 on the .Net platform and have the following html in my view. As you can see the names are the same to distinguish which button is pressed when going into the Controller to take the proper action.

<tr>
    <td>
        <input type="submit" name="submitbutton" id="btnRefresh" value='Refresh' />
    </td>
        @if (Model.ShowGeneratePDFBtn == true)
        {
            <td>
                <input type="submit" name="submitbutton" id="btnGeneratePDF" value='Generate PDF' />
            </td>
        }
</tr>

However, when the second ("Generate PDF") button is pressed, I need to disable it so the user won't be able to press it again while a process is taking place. If I disable it, it no longer appears in the html as a control (which is understandable).

Here is the js:

$('#btnGeneratePDF').click(function () {
    DisableGeneratePDF();
});

function DisableGeneratePDF() {
    $('#btnGeneratePDF').attr("disabled", true);
}

In the Controller, the value of the button when pressed is null instead of "Generate PDF", so the proper action doesn't get executed.

Here is the first line in the Controller:

[HttpPost]
public ActionResult ProcessForm(string submitbutton, ViewModelTemplate_Guarantors model, FormCollection collection)

Here is the first line in the View. I also tried it with FormMethod.Post, but since I'm not going to another page the AjaxOption would be more efficient.

@using (Html.BeginForm("ProcessForm", "Home", new AjaxOptions { HttpMethod = "POST" }))

How can I successfully pass the "Generate PDF" value to the Controller when I disable the button?

Upvotes: 0

Views: 72

Answers (1)

Jarrett Meyer
Jarrett Meyer

Reputation: 19573

Create a hidden form value and put this in your view model. Then set that value in you click event handler.

To your model, add the following

public class Guarantors
{
    public bool ShouldGeneratePdf { get; set; }
}

To your view, add

@Html.HiddenFor(x => x.ShouldGeneratePdf)

To your JavaScript

$('#btnGeneratePDF').click(function () {
    DisableGeneratePDF();
    $('#ShouldGeneratePdf').val('True');
});

function DisableGeneratePDF() {        
    $('#btnGeneratePDF').attr("disabled", true);
}

That ought to do it.

Upvotes: 1

Related Questions