Reputation: 89
I'm trying to get the value of some checkbox which is selected using ajax and jquery. Right now I have all items listed on my site, but I want to let user to check the checkbox to get the selected items.
Controller:
[HttpGet] public JsonResult getCategoryItems(){}
How can it be done?
View:
@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"})
}
As you can see, the code above is just counting the items in category to list as checkbox. I just want to let a user to check the checkboxes, however so user can get the items by check an item from checkboxes.
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;
}
Upvotes: 0
Views: 1906
Reputation: 218722
Your question is a little confusing. But i am assuming when user select a checkbox, you want to send the Id of that checkbox to your action method and get some response back which you will use for updating your UI.
As Stephen Muecke mentioned in the comments, Your current code is generating duplicate Id values for the checkboxes. You should not have duplicate ids for your form elements.
Assuming your each item in your HesViewModel
has an Id
property (with unique values) which we will use to send to the server.
When you render the checkBox, you might pass in the html attributes for rendering css class (We will use for our jQuery selection to listen to any changes to the checkbox's state) and an Id ( we will use this unique value to send to server)
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})
}
Now we will have some jQuery code to listen to changes in the checkboxes. When it is checked, We will use the Id attribute value and send it to server using 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");
});
}
});
});
Ofcourse now your action method should accept an id as parameter
[HttpGet]
public JsonResult getCategoryItems(int id)
{
// to do : Send some useful data back.
return Json(new { Data :"Good"},JsonRequestBehaviour.AllowGet);
}
Upvotes: 1