带有下拉列表的MVC 3 Webgrid,在回发时获得选定的值

时间:2012-10-09 19:35:27

标签: asp.net-mvc drop-down-menu postback viewmodel webgrid

我有一个带有dropdownlist的webgrid,并且onchange它会回发页面。我正在尝试获取下拉列表的选定值。

以下是我的控制器。

 public ViewResult Index()
            {
                //var albums = db.Albums.Include(a => a.Artist).Include(a => a.Genre);

                var model = new AlbumActionModel { Actions = new[] { new SelectListItem { Text = "Accept", Value = "Accept" }, new SelectListItem { Text = "Deny", Value = "Deny" } }, Albums = db.Albums.Include(a => a.Artist).Include(a => a.Genre) };
                return View(model);
            }

以下是我的观点。

<div>
   @{
    WebGrid grid = new WebGrid(Model.Albums, defaultSort: "Title", selectionFieldName: "SelectedRow");
    }
   @using (Html.BeginForm("Index", "Album", FormMethod.Post, new { id = "TheForm" }))
   {
    @grid.GetHtml(columns: grid.Columns(grid.Column("Edit",
                                                    format: @<text> @Html.ActionLink("Edit", "Edit", new { id = item.AlbumId })></text>),
                           grid.Column("AlbumId"),
                           grid.Column("Title"),
                           grid.Column("Action",
                                        format:
                                            @<span>
                                            @{var index = item.AlbumId.ToString();}
                                            @Html.DropDownList("Actions" +((string)index), Model.Actions, "--Select One--", new { onchange = "this.form.submit();" })
                                            </span>),
                           grid.Column("Delete",
                                        format: @<text> @Html.ActionLink("Delete", "Delete", new { id = item.AlbumId })></text>)))
</div>

提前致谢。

1 个答案:

答案 0 :(得分:0)

在您的下拉列表中尝试以下语句:

@Html.DropDownList("Actions" +((string)index), Model.Actions, "--Select One--",new { @onchange = "Submit(this.value);" })

现在在<script>标记中写一个函数,将其发布到页面

    <script type="text/javascript">
    function Submit(e)
    {
    //write it to post to the controller using ajax 
    $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: '@Url.Action("Submit", "ControllerName")',
                    data: ({ value: e}), 
                    success: function (result) {
                        //do something
                    }
                        ,
                    error: function (result) {
                        //do something
                    }
                });
    }
</script>

希望这有帮助。