boilers222
boilers222

Reputation: 1989

How do I pass a parameter when submitting an form in javascript to a MVC controller?

I have a .cshtml page with several buttons like this:

<input id="btnViewHistory" type="submit" name="postFunction" value="View History" />
<input id="btnComments" type="submit" name="postFunction" value="Comments" />

When the form is submitted, the parameter "postFunction" is passed to the controller and I can check what button was pressed:

[HttpPost]
    public ActionResult LabApprovals(ModelApproval model, int page, string postFunction)
    {
        if (postFunction == null)
        {
          ...
        }
        else if (postFunction == "View History")
        {
            ...
        }
        else if (postFunction == "Comments")
        {
            ...
        }
        else
        {
            return View(model);
        }
    }

So if you click the "View History" button, when the controller is hit postFunction="View History".

I need to submit the form from Javascript for another reason other than a button press. I have the Javascript to submit the form, but how do I pass a parameter?I'm trying to get postFunction to have a value such as "Changed Page" when the controller is reached.

    $("#txtPage").kendoNumericTextBox({
    change: function () {
        $("#formLabApprovals").submit();
    }
    });

Upvotes: 0

Views: 1157

Answers (3)

boilers222
boilers222

Reputation: 1989

This is similar to both the other answers, but I thought I'd post this as well. It's what I finally did to get it to work. I found this page that was helpful: jQuery - add additional parameters on submit (NOT ajax).

var input = $("<input>")
    .attr("type", "hidden")
    .attr("name", "postFunction").val("ChangePage");
$('#formLabApprovals').append($(input));
$("#formLabApprovals").submit();

Upvotes: 1

Benjamin Smith
Benjamin Smith

Reputation: 11

You can use the .val(*value*) method to assign the value attribute programmatically.

$("#txtPage").kendoNumericTextBox({
change: function () {
    $("#formLabApprovals").val("Changed Page");
    $("#formLabApprovals").submit();
} });

jQuery(#id).val() VS getElementById(#id).value is another article with some related information about using .val().

Upvotes: 1

No Refunds No Returns
No Refunds No Returns

Reputation: 8336

Often one will put script-supplied values in a hidden field so they flow through to your controller but are invisible to the user. Set the field's value in your existing script.

<input type="hidden" name="fieldFromScript" />

Upvotes: 4

Related Questions