[英]How to display a table of selected items once I select a value from the first drop down list using classic asp, jquery and ajax?
[英]How to display items from checkbox list using jquery ajax
我試圖獲取使用ajax和jquery選擇的某些復選框的值。 現在,我的網站上列出了所有項目,但我想讓用戶檢查復選框以獲取選定的項目。
控制器:
[HttpGet] public JsonResult getCategoryItems(){}
如何做呢?
視圖:
@for (int i = 0; i < Model.CarsCount.Count(); i++)
{
var cars = Model.CarsCount.ElementAt(i);
<span class="label label-info">
@cars.CategoryName <span class="badge">@cars.CategoryCount</span
</span>
@Html.CheckBox(cars.CategoryName, cars.isChecked, new { id = "carsCheckbox"})
}
如您所見,上面的代碼只是將類別中的項目計數為復選框。 我只想讓用戶檢查復選框,但是用戶可以通過檢查復選框中的項目來獲取項目。
private IEnumerable<CarViewModel> GetListOfCars()
{
var listOfcars = this.Data.cars.All()
.Select(t => new CarViewModel
{
Id = t.Id,
Title = t.Title,
Price = t.Price ,
FileName = t.FileName
});
return listOfcars;
}
您的問題有點令人困惑。 但是我假設當用戶選中一個復選框時,您想將該復選框的ID發送給您的操作方法,並獲得一些響應,以用於更新UI。
正如Stephen Muecke在評論中提到的那樣,您當前的代碼正在為復選框生成重復的Id值。 您的表單元素不應有重復的ID。
假設您的HesViewModel
中的每個項目都有一個Id
屬性(具有唯一值),我們將使用該屬性將其發送到服務器。
呈現checkBox時,您可能會傳入html屬性以呈現css類 (我們將使用jQuery選擇來偵聽對復選框狀態的任何更改)和一個ID (我們將使用此唯一值將其發送到服務器)
for (int i = 0; i < Model.HesViewModels.Count(); i++)
{
var cars = Model.HesViewModels.ElementAt(i);
<span class="label label-info"> @cars.DetailRasonCode </span>
@Html.CheckBox(cars.CategoryName,
cars.isChecked, new { @class = "myCheck", id = cars.Id})
}
現在,我們將有一些jQuery代碼來偵聽復選框中的更改。 選中后,我們將使用Id屬性值,並使用ajax將其發送到服務器。
$(function () {
$("input.myCheck").change(function(e) {
var _this = $(this);
if (_this.is(":checked")) {
var id = _this.attr("id");
alert(id);
//Let's make the Ajax call now
var url = "@Url.Action("getCategoryItems","Home")?id=" + id;
$.get(url, function () {
}).done(function (res) {
alert('response from server received');
console.log(res);
//Use the response as needed to update your UI
}).fail(function () {
alert("error");
});
}
});
});
當然,現在您的操作方法應該接受一個id作為參數
[HttpGet]
public JsonResult getCategoryItems(int id)
{
// to do : Send some useful data back.
return Json(new { Data :"Good"},JsonRequestBehaviour.AllowGet);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.