如何将参数传递给控制器​​函数

所以我有一个这样的表格:


@using (Html.BeginUmbracoForm<DataController>("SetYear", null, new { @id = "yearDropdown" }))

{

    <div class="form-group">

        <select id="Year" name="Year" class="form-control">


            @if (objModel.Annums != null)

            {

                foreach (Int32 intYear in objModel.Annums.OrderByDescending(x => x).ToList())

                {

                    <option 

                        @if (intYear == DateTime.Now.Year) 

                        { 

                            <text>selected</text> 

                        } 

                        value="@intYear">

                        @intYear

                    </option>

                }

            }


        </div>

    </div>

}

其中一部分jQuery会在更改时提交表单(我意识到这可以内联完成):


if ($("#yearDropdown").length) {

    $("#Year").on('change', function () {

        $("#yearDropdown").submit();

    });

}

我想要做的是将 传递Year给控制器中的函数,如下所示:


public void SetYear (Int32 intYear)

{

    System.Web.HttpContext.Current.Session["Year"] = intYear;

}

这可以仅使用 C# 来完成吗?还是我必须将 a 附加querystring到表单 URL 上?


繁花如伊
浏览 84回答 1
1回答

皈依舞

控制器中的方法应该是一个 Action 并且它应该返回一个 ActionResult:[HttpPost]public ActionResult SetYear (Int32 intYear){&nbsp; &nbsp; System.Web.HttpContext.Current.Session["Year"] = intYear;&nbsp; &nbsp; return View();}此外,Select元素名称必须与 Action 方法的参数名称 ( intYear) 匹配:@using (Html.BeginUmbracoForm<DataController>("SetYear", null, new { @id = "yearDropdown" })){&nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; <select id="Year" name="intYear" class="form-control">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @if (objModel.Annums != null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach (Int32 intYear in objModel.Annums.OrderByDescending(x => x).ToList())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @if (intYear == DateTime.Now.Year)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <text>selected</text>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value="@intYear">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @intYear&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>}
打开App,查看更多内容
随时随地看视频慕课网APP