Michael Witt
Michael Witt

Reputation: 1712

MVC Form Form element not going to controller action

I think I must be doing something silly, but if anyone can point out what I'm doing wrong, that would be great!

I have a form in a Razor view like:

            @using (Html.BeginForm("Index", "SiteKPIs", FormMethod.Get))
            {
                <table>
                    <tr>
                        <td style="margin-right: 25px;">Site</td>
                        <td>@Html.DropDownList("siteId", new SelectList(ViewBag.Sites, "SiteID", "SiteDisplayName"))</td>
                    </tr>
                    <tr>
                        <td>Range</td>
                        <td>
                            <select id="rangeId"><option value="0">test</option></select>
                            <input class="btn btn-primary btn-xs" type="submit" value="Go" />
                        </td>
                    </tr>
                </table>
            }

The signature of my controller action looks like:

    public ActionResult Index(int? siteId, int? rangeId)

I get a value for siteId, but rangeId is null. What am I doing wrong?

Upvotes: 0

Views: 63

Answers (2)

James
James

Reputation: 1501

I believe it would be better to use a HtmlHelper for a dropdownlist, like so:

<div class="form-group">
    <label for="range">Range</label><br />
    @Html.DropDownList("RangeID", null, "Please select...", 
        new { @class = "form-control", id = "rangeID" })
</div>

Then, inside your controller, you can populate the dropdownlist there, with something like:

List<SelectListItem> options = new List<SelectListItem>();

options.Add(new SelectListItem { Text = "Test", Value = "0"});
// and so on...

You can then use a ViewBag in your controller and make it equal to this list, like so:

ViewBag.RangeID = options;

Upvotes: 0

freshbm
freshbm

Reputation: 5622

If you want to use plain html select, then you need to set Name attribute of your select to expected param name in your Controller Action:

<select id="rangeId" name="rangeId"><option value="0">test</option></select>

But my suggestion is to use DropDownList helper either way.

Upvotes: 1

Related Questions