How to pass a filtered list into Action parameters

2019-09-12 20:49发布

问题:

Hi I have a WebGrid with two columns:

1-Name
2-Action binded to another controller action. On click i will re-direct to that action, parameter should be a List of List<Test> items.

Output: Request goes to Controller but parameter is empty colelction, am i missing anything.

View:

@model IEnumerable<Test>
<div id="testGrid">
    @{
        var grid = new WebGrid(ajaxUpdateContainerId: "testGrid", canSort: true);
        grid.Bind(Model);   
        @MvcHtmlString.Create(
            @grid.GetHtml(
                columns: grid.Columns
                    (
                        grid.Column(Html.DisplayNameFor(model => model.Name).ToHtmlString(),
                        header: Html.DisplayNameFor(model => model.Name).ToHtmlString()),
                        grid.Column("Action", header: "Action", format: @<a href="@Url.Action("LoadTest", "NewController", 
                        new
                        {
                            ingredients = Model.Select(t=>t.Id==@item.Id).ToList()
                        }
                        )" class="edit-btn"></a>)  
                    )
                ).ToString()
             )
    }
</div>

Controller code

List coming empty.

public ActionResult LoadTest(List<Test> testItems)
        {
            //...test code.
        }

回答1:

Your Url.Action is creating a different variable than what your controller is expecting:

Either change your action from ingredients, to testItems:

 grid.Column("Action", header: "Action", format: @<a href="@Url.Action("LoadTest", "NewController", 
                        new
                        {
                            testItems = Model.Select(t=>t.Id==@item.Id).ToList()
                        }

or change your controller to expect a parameter called ingredients:

public ActionResult LoadTest(List<Test> ingredients )
        {
            //...test code.
        }

Also, did you update your Global.asax to expect a route of this type? This example is assuming you keep the name testItems as your parameter.

        routes.MapRoute(
         "Test route", // Route name
         "NewController/{action}/{testItems}", // URL with parameters
         new { controller = "NewController", action = "LoadTest" } // Parameter defaults
     );