Find ids of checked checkboxes with jQuery in MVC

2019-07-24 13:43发布

问题:

I have a Field model, which represents a certain field (Name, Description, ...)

class FieldModel : EntityModel
{    
    ...
    public bool ToCopy { get; private set; }
    public string Id {get; private set; }
    ...
}

An Index model, which has a collection of Fields:

class EntityModel
{
    ...
}

class IndexModel
{
    public IEnumerable<EntityModel> Fields { get; private set; }
}

Controller for copy, that should accept ids of fields to copy:

public void CopyFields(string[] fieldsIds)
{
    ...
}

And I need to select certain fields to copy by checkboxes. So in the vew for Field I added

@Html.CheckBoxFor(x => x.IsSelectedForCopy)

In the view for Index

<button onclick="onCopyClick('@Model');" type="button" class="btn showButton">Copy Fields</button>

And now I need to write a script to select all checked fields and send their Ids to the controller. I have zero experience with Javascript/jQuery, so could someone help me with that?

回答1:

This should get you started at least ;)

You give jQuery some css selectors and it gives you the objects that match...

$("input :checked").each(function() {
    alert($(this).attr("id"));
});

Depending on how you want to send them, you could then append each id to a hidden field on a form like so:

$("input :checked").each(function() {
    var tmp = $("#myHiddenField").val();
    tmp += " " + $(this).attr("id"));
    $("#myHiddenField").val(tmp);
});
$.ajax("TheURLToPostTheDataTo", 
    {data: [
        {idsToSend:$("#myHiddenField").val()}
    ], 
    success:  function() { 
         alert("Done"); 
    }
});

Then submit, and on the serverside trim and split by space?