Athanasios Kataras
Athanasios Kataras

Reputation: 26352

MVC 4 submit specific form value

I want to know how to submit specific form values from an MVC 4 application using razor.

I have the following senarion.

2 Drop down lists. The first is populated in the controller using Model data listing a set of type (autoselect a default value the first time). The second is populated by type objects (autoselect the first one if the postback is coming from the first dropdown list).

What I want to do is this. If the 1st dropdownlist is doing the postback, I want only the selected value of the first list to be posted and the dropDownList2 to be 0.

If the second dropdownlist is causing the postback I want both values.

public ActionResult Index(int dropDownList1 = 0, int dropDownList2 = 0)
{
   // Get data for the dropdown lists
}

This is the view file

<p>
@Html.ActionLink("Create New", "Create")
@using (Html.BeginForm("Index","EditItems",FormMethod.Get)){     
     <p>Γονείς τύπων: @Html.DropDownList("dropDownList1") </p> 
     <p>Τύποι σχολείων: @Html.DropDownList("dropDownList2")  </p> 
    } 
</p>

@section Scripts {
    <script type='text/javascript'\>
        $("#parentUnit").change(function () {
            $(this).parents('form').submit();
        });

        $('#childUnit').change(function () {
            $(this).parents('form').submit();
        });
    </script>
}

Thanks in advance

Upvotes: 0

Views: 822

Answers (2)

pawan
pawan

Reputation: 1

<!DOCTYPE html>
<html>
<body>

<form action="demo_form.asp" method="get">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <button type="submit">Submit</button><br>
  <button type="submit" formaction="demo_admin.asp">Submit as admin</button>
</form>

<p><strong>Note:</strong> The formaction attribute of the button tag is not supported in Internet Explorer 9 and earlier versions.</p>

</body>
</html>

>

Upvotes: 0

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

In a normal post situation, you can't submit specific values. All form fields will be submitted. There is no way to prevent this.

What you can do, however is one of three things:

1) You can us javascript to change the various fields to clear the ones you don't want to send, and set the correct values in the ones you do want to send.

2) You can use Ajax to post, and then you can control what data is posted.

3) You could have several hidden forms, and when the user clicks submit you could use javascript to copy just the values you want to submit to the forms with just those fields, then submit that form via javascript.

Upvotes: 2

Related Questions