ASP.NET mvc Ajax Helper DropDownListFor 将选定的项目值作为参数发送到控制器

ASP.NET mvc Ajax Helper DropDownListFor send selected item value as parameter to controller

问题 我希望我的 Ajax 表单将所选 DropDownListFor 的值传递给控制器​​,但我不明白为什么控制器没有取任何值。 我正在使用 ASP.NET MVC,我想尽可能多地使用辅助函数。

查看

@using (Ajax.BeginForm(new AjaxOptions {
HttpMethod = "Get", 
UpdateTargetId = "UserResults",
InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace }))
{
    @Html.DropDownListFor(Model => Model.Roles, new SelectLi(ViewBag.Groups 
    as System.Collections.IEnumerable, "Value", "Text"), "Select a group",
    new { id = "Value", onchange = "$(this.form).submit();" })
}
@Html.Partial("_UsersGroup", ViewData)

控制器

public ActionResult test(int? selectGroup)
{

// Generate dropdownlist Groups
List<SelectListItem> groupList = new List<SelectListItem>();
var query = from s in db.Roles select s;
if (query.Count() > 0)
{
    foreach (var v in query)
    {
        groupList.Add(new SelectListItem { Text = v.Name, Value =
        v.ID.ToString() });
    }
}
ViewBag.Groups = groupList;
// End

// This part is supposed to take the passed value as parameter
if (selectGroup == null)
{
    // To do code comes here, which takes selectGroup as parameter
}

详情

表单应将基于选择的值传递给控制器​​,控制器将其作为 "selectGroup"。

ps。第一次提问,如有错误请见谅

你方法的参数需要匹配控件的名称name="Roles"所以方法应该是

public ActionResult test(int? roles)

您的代码的其他潜在问题

您的控制器生成 List<SelectListItem> 供下拉列表使用。不需要从中创建新的 SelectList(即 IEnumerable<SelectListItem>)的不必要的额外开销。视图代码可以简单地是 @Html.DropDownListFor(m => m.Roles, (IEnumerable<SelectListItem>)ViewBag.Groups, "Select a group")

不要在表达式中使用Model(大写M)。如果您在视图中对模型进行任何其他引用(例如 @Model.SomeProperty),您将收到错误消息。使用小写 model => model.somProperty 是可以的,但您可以简单地使用 m => m.someProperty

助手将生成一个 id 属性(在您的情况下为 id="Role"),因此您似乎不清楚为什么要添加 new { id = "Value", ..},尤其是因为您似乎没有引用元素由其 id anywhere

学习使用 Unobtrusive Javascript 而不是用行为标记来污染你。删除 onclick 属性并使用 $('#Roles').change(function() { $('form').submit(); });