[英]How to get a @html.Checkbox to update a @html.dropdownList
[英]How to get the values of Check Box(@Html.CheckBox) through JQuery JSON data
我想通過JQuery將值(已檢查或未檢查)綁定到MVC 3中的@Html.CheckBox
。
這是我的HTML-
@using (Html.BeginForm())
{
IEnumerable<SelectListItem> Brands = ViewBag.GetBrands;
foreach (var item in Brands)
{
@Html.CheckBox("Brands", false, new{value = item.Value});
<label>@item.Text</label><br />
}}
這是我試過的 -
function test {
var url = "/OfficeManagement/Offices/GetOfficeConfiguration";
var stringToReverse = rowData.ID;
var noCache = Date();
$.get(url, { officeID: stringToReverse, "noCache": noCache }, function (data) {
for(int i=0;i<data.Configuration.OfficeBrands.count;i++)
{
$('#Brands').attr('checked', data.Configuration.OfficeBrands[i]);
}
...............
}
**$("#Brands").attr("checked"," ")**
在上面一行中,您使用ID訪問該復選框,但如果有多個復選框具有相同的ID,則它僅適用於第一個復選框。 因此,為所有復選框添加一個class屬性,然后使用該類訪問它們。
為了使它工作,你可以嘗試如下,
創建具有唯一名稱的復選框,如下所示:
int counter = 0;
foreach (var item in Brands)
{
@Html.CheckBox("Brands" + counter, false, new{value = item.Value});
counter++;
}
它將創建有點像這樣的html標記:
<input type="checkbox" name = "Brands0" />
<input type="checkbox" name = "Brands1" />
<input type="checkbox" name = "Brands2" />
然后在jquery中你可以像這樣檢索值:
for(int i=0;i<data.Configuration.OfficeBrands.count;i++)
{
$( "input[name*='"Brands"+i+"]"').attr('checked', data.Configuration.OfficeBrands[i]);
}
這對我有用 -
$.each(data.Configuration.OfficeBrands, function(i, brand) {
$(':checkbox[Value="' + brand.ID + '"]').prop('checked', true);});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.