How to perform a simple multiple selection in a table ASP.NET MVC4

后端 未结 2 711
情歌与酒
情歌与酒 2021-01-27 19:45

Here is what my view looks like:

@model Affiliate


相关标签:
2条回答
  • 2021-01-27 20:17

    Based off your comments, you don't seem to be looking for the most "correct" answer, but rather just a quick and dirty "how would I do this" answer. If you just want to pass the list, you could setup your controller action like this:

    public ActionResult MyAction(int[] id)
    {
        ...
    }
    

    Or, you seem to indicate it is strongly typed to a view model with a property that contains a List (I would shorten the name of the property, you'll see why in a second).

    In javascript, the easiest thing to do would be to use jQuery to bind a click event on your hyperlink that gets the list of items that are checked and appends that to the query string.

    $("#myLink").click(function()
    {
        var url = "site.com/action?";
        var ids = $(".table").find("input:checked");
    
        ids.each(function()
        {
            url += "id=" + $(this).val() + "&"
        });
    
        window.location = url;
    });
    

    Basically, you want to create one long query string with the action parameter's name repeated over and over, which identifies an array. It looks something like this (id is for int[] id in MyAction):

    id=15&id=20&id=25&id=30&....
    

    And then once the query string is built, redirect the user to that url. MVC should then be able to bind that to an array and you're all set.

    That's basically the idea, anyway; the syntax and the javascript I wrote could be way off so don't copy my code and expect it to work as is - I wrote that off the top of my head. If your action is bound to a viewmodel, then you need to set the parameter in the query string to the name of the property of your model:

    selectedids=1&selectedids=2&selectedids=3...
    

    Or, if the array is a property of an object, which is a property of the model...

    model.selectedids=1&model.selectedids=2&model.selectedids=3...
    

    You'll just need to play around with it some.

    0 讨论(0)
  • 2021-01-27 20:37

    Use html checks inside form tag ( you could use helpers too) and post the model to a post action. MVC will serialize the model automatically

    0 讨论(0)
提交回复
热议问题