Andy Johnston
Andy Johnston

Reputation: 487

Pass Input Parameter to ActionResult MVC 4

I have the following .cshtml

    <fieldset>
      <legend></legend>
      <p>
        @using (Html.BeginForm("PlayerList", "Players", new{id = "Id"}, FormMethod.Post))
        {
            @Html.DropDownListFor(Model => Model.Teams, new SelectList(Enumerable.Empty<SelectListItem>(), "Id", "Name"),
               "Select a Team", new { id = "ddlTeams" }) <input type="submit" value="Get Player List" />
        }
      </p>
    </fieldset>

The DropDownList is filled from some javascript:

$("#ddlComps").change(function () {
        var compid = $(this).val();
        $.getJSON("../Players/LoadTeamsByCompId", { compid: compid },
                     function (teamsData) {
                        var select = $("#ddlTeams");
                        select.empty();
                        select.append($('<option/>', {
                            value: 0,
                            text: "Select a Team"
                        }));
                        $.each(teamsData, function (index, itemData) {
                            select.append($('<option/>', {
                                value: itemData.Value,
                                text: itemData.Text
                            }));
                        });
                     });
    });

Why is it when I click the submit button, no Id parameter is passed to the ActionResult PlayerList?

Upvotes: 3

Views: 4210

Answers (3)

Jasen
Jasen

Reputation: 14250

If you watch the network requests from your browser's debug console you will see that your form is posting Teams but your action is expecting id which never is sent so defaults to 0. It's not being sent because you don't have a field named id.

Change your action to

[HttpPost]
public ActionResult PlayersList(int teams = 0)
{
    ...
}

Upvotes: 0

BrunoLM
BrunoLM

Reputation: 100351

You said your ActionResult looks like (notice the 's')

public ActionResult PlayersList(int id = 0){...}

But your BeginForm action is

PlayerList

So my bet is that you are posting to the wrong action.

You also have to set the field name attribute to the same you expect on your action.

Upvotes: 0

Haney
Haney

Reputation: 34832

Specify a name parameter on your DropDownList that indicates that the value is for the "ID" parameter. name="id" and that should solve it.

Upvotes: 1

Related Questions