在MVC中使用jQuery查找选中的复选框的ID [英] Find ids of checked checkboxes with jQuery in MVC
问题描述
我有一个Field模型,它代表一个特定的字段(名称,描述等)
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; }
}
用于复制的控制器,该控制器应接受要复制的字段ID:
Controller for copy, that should accept ids of fields to copy:
public void CopyFields(string[] fieldsIds)
{
...
}
我需要选择某些字段以通过复选框复制.因此,在Field的誓言中,我添加了
And I need to select certain fields to copy by checkboxes. So in the vew for Field I added
@Html.CheckBoxFor(x => x.IsSelectedForCopy)
在索引视图中
<button onclick="onCopyClick('@Model');" type="button" class="btn showButton">Copy Fields</button>
现在我需要编写一个脚本来选择所有选中的字段并将其ID发送给控制器.我对Javascript/jQuery的经验为零,有人可以帮我吗?
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?
推荐答案
这至少可以帮助您入门;)
This should get you started at least ;)
您为jQuery提供了一些CSS选择器,它为您提供了匹配的对象...
You give jQuery some css selectors and it gives you the objects that match...
$("input :checked").each(function() {
alert($(this).attr("id"));
});
根据您希望如何发送它们,然后可以将每个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?
这篇关于在MVC中使用jQuery查找选中的复选框的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!