send multiple checkbox vales to controller using ajax in asp.net mvc - javascript

i have download the Microsoft Music-Store application so i am making some changes in that so what i am changing is that Album model consisting of (id, title, genreId, artistid......) so i want to display list of Album based on genreid using Checkboxes whatever the checkboxes i clicked the list should be displayed so i written the code like this.
here i have small problem what that means when i go to GenericList view where all genre name are displaying(showing in every genre name with checkbox this checkboxes are unchecked) but list of album is not showing (where all checkboxes are unchecked list should be displayed) when every i checked some checkboxes it displaying exactly but unchecked all checkboxes list of album are not showing.so please help me what changes i have to make
Controller:
`public ActionResult GenericList()
{
ViewBag.Generic = db.Genres.ToList();
return View();
}`
public ActionResult _GenreList(string cbk)
{
var listIds = new List<Int32>(Array.ConvertAll(cbk.Split(','), Convert.ToInt32));
var list = from a in db.Albums
select a;
if (cbk != null)
{
list = from l in db.Albums
where listIds.Contains(l.GenreId)
select l;
}
else
{
list= from a in db.Albums
select a;
}
return PartialView(list);
}
ActionResult
<ul id="checkboxFilter">
#foreach(var item in ViewBag.Generic)
{
<li>
<div class="custom-checkbox">
<input type="checkbox" class="cbk" id="#item.GenreId.ToString()" /> #item.Name
</div>
</li>
}
</ul>
Javascript
<script>
$(document).ready(function () {
$('.cbk').change(function () {
var ID = "";
$('.cbk').each(function (index, val) {
if ($(this).is(':checked')) {
ID += $(val).attr("Id") + ",";
alert('id Name: ' + ID);
}
});
var data = {};
data.cbk = ID.slice(0, ID.length - 1);
if (ID != 0) {
$.ajax({
url: '/Home/_GenreList',
method: 'POST',
data: data,
success: function (data) {
$("#Generic_list").html(data);
},
error: function () {
alert("Something went Worng.");
}
});
}
});
});

You need to set the same name for all the checkboxes in the group e.g. "name"="genres"
and value attribute to the value you want to pass to the controller e.g. "value="#item.GenreId.ToString()".
Then in the controller, you'll receive a genre array e.g.
public ActionResult _GenreList(string[] genres)

Related

Loading partial view depending on dropdown selection in MVC

I apologize I am still fairly new to MVC. I currently have a dropdownlist with some options. What I would like to do is depending on the dropdownlist value that I select then I should be able to render a partial view. I want the partial view to load as soon as the user selects from the dropdownlist.
Also, I am able to render my partial view but it's not returning what I need. When I select from the dropdownlist it does not take the functionID..it just returns all of the items regardless of the functionID.
I want the partial view to render based off the functionID.
Thank you very much. Any help is very much appreciated it.
Main View
#Html.DropDownListFor(m => m.FunctionID, new
SelectList(Model.functionList, "FunctionID", "Name"), "Select
Function", new {#id="id"})
<div id="partialPlaceHolder">
</div>
Partial View
#foreach (var items in Model.itemTypeList)
{
<pre> #items.Definitions</pre>
}
Controller
[HttpGet]
public ActionResult ViewOverview()
{
List<Function> functionList;
List<ItemType> itemTypeList;
using (BusinessLogic BLL = new BusinessLogic())
{
functionList = BLL.GetFunctionList();
itemTypeList = BLL.GetItemTypesList();
}
Words viewModel = new Words();
MetricDefinitions(viewModel);
return View(viewModel);
}
[HttpGet]
public ActionResult GetWords()
{
List<Function> functionList;
List<ItemType> itemTypeList;
using (BusinessLogic BLL = new BusinessLogic())
{
functionList = BLL.GetFunctionList();
itemTypeList = BLL.GetItemTypesList();
}
Words viewModel = new Words()
{
itemTypeList = itemTypeList,
functionList = functionList
};
return PartialView("_ViewWords", viewModel);
}
private void MetricDefinitions(Words model)
{
List<Function> functionList;
List<ItemType> itemTypeList;
using (BusinessLogic BLL = new BusinessLogic())
{
functionList = BLL.GetFunctionList();
itemTypeList = BLL.GetItemTypesList();
}
model.functionList = functionList;
model.itemTypeList = itemTypeList;
}
javascript
$(document).ready(function () {
$('#id').change(function () {
var selectedID = $(this).val();
$.get('/Home/GetWords/' + selectedID, function (data) {
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});
});
});
I have added NetFiddle. It works here
Can you try to add selectedItem param into action and use jquery .load() function to get partial result into your target element.
[HttpGet]
public ActionResult GetWords(int selectedItem) // add your selectedVal value in controller
{
.....
}
jquery
// it is going to parse partial view into target div
$("#id").on("change", function(){
var url = '#Url.Action("GetWords", "Home")' + "?selectedItem=" + $(this).val();
$("#partialPlaceHolder").load(url, function(){
console.log("It worked");
$('#partialPlaceHolder').fadeIn('fast');
})
})

How do I populate a select input based on 2 radio button values, from mysql

So I have a registration form for archery contests and I want users to select 2 things (their age category and their bow type).
Once those 2 are selected, I want the next field (select) to show up and be populated with information from my mysql database.
This field is a selection of shooting levels, differenciated in classes.
In the database, I have 4 tables.
1 for age category (id, name)
1 for bow type (id, name)
1 for shoot level (id, name)
1 table to link all above (id, ac_id, bt_id, sl_id)
So based on radio 1 being clicked and radio 2 being clicked, I want to fire a query on the link table to only get the shooting levels which belong to the 2 radio values..
Can anyone please help me with this?
Try this:
$('#age').click(function(){
var age = $(this).val();
var bow = $('#bow').val();
function getShootingLevel(age, bow);
});
$('#bow').click(function(){
var age = $('#age').val();
var bow = $(this).val();
function getShootingLevel(age, bow);
});
function getShootingLevel(age, bow)
{
// ajax call
}
P.S. You can also check if radio is selected or not.
I got it :)
$(document).ready(function() {
$('input[type=radio][name=leeftijdscategorie]').change(function() {
if($('input[type=radio][name=leeftijdscategorie]').is(':checked')) {
if($('input[type=radio][name=schiettechniek]').is(':checked')) {
// Do stuff
GetLevels($('input[name=leeftijdscategorie]:checked', '#inschrijfformulier').val(),$('input[name=schiettechniek]:checked', '#inschrijfformulier').val())
}
}
});
$('input[type=radio][name=schiettechniek]').change(function() {
if($('input[type=radio][name=schiettechniek]').is(':checked')) {
if($('input[type=radio][name=leeftijdscategorie]').is(':checked')) {
// Do stuff
GetLevels($('input[name=leeftijdscategorie]:checked', '#inschrijfformulier').val(),$('input[name=schiettechniek]:checked', '#inschrijfformulier').val())
}
}
});
});
function removeOptions(selectbox) {
var i;
for(i = selectbox.options.length - 1 ; i >= 0 ; i--) {
selectbox.remove(i);
}
}
function GetLevels(agetype,bowtype) {
removeOptions(document.getElementById(\"schietklasse\"));
$.ajax({
url: '/info/wscript.php',
data:
{
agetype: agetype,
bowtype: bowtype
},
type: 'post',
dataType: 'json', // returns response data as json//
success: function(output) {
var selectBox = document.getElementById(\"schietklasse\");
var options = output; //JSON.parse(output);
for(var i = 0, l = options.length; i < l; i++){
var option = options[i];
selectBox.options.add( new Option(option.text, option.value, option.selected) );
}
}
});
}
I basically made this radio check seperate (so double) because I want people to be able to change their choice. Now, it fires a POST to a php file which gets the information and returns it as JSON.

how to append value in select tag inside dynamic table

im adding table row data using json response. here is my code
var i;
for (i = 0; i < result.length; i++) {
$.get('LoadserviceSplit', {
"sectcode" : result[i]
},
function (jsonResponse) {
if (jsonResponse != null) {
var table2 = $("#table_assign");
$.each(jsonResponse, function (key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['serviceId']);
rowNew.children().eq(1).text(value['title']);
rowNew.children().eq(2).html('<input type="text" id="date_set" name="date_set"/>');
rowNew.children().eq(3).html('<input type="text" id="date_set1" name="date_set1"/>');
rowNew.children().eq(4).html('<input type="text" id="date_set2" name="date_set2"/>');
rowNew.children().eq(5).html('<select class="status1" id="status1">');
rowNew.appendTo(table2);
});
}
});
var pass_unit_code = "001";
$.get('LoadDivisionCodeServlet', { //call LoadDivisionCodeServlet controller
unitCode : pass_unit_code //pass the value of "sample" to unitCode:
}, function (jsonResponse) { //json response
var select = $('#status1'); //select #status1 option
select.find('option').remove(); //remoev all item in #divcode option
$.each(jsonResponse, function (index, value) {
$('<option>').val(value).text(value).appendTo(select); //response from JSON in array value{column:value,column:value,column:value}
});
});
}
it works fine except the select tag part. only the first row of table have value. the rest has no value. i want all drop-down list inside the table has same value.. can anyone help me about this.
Take a look at
rowNew.children().eq(5).html('<select class="status1" id="status1">');
You're creating new select elements in a $.each and assigning the same id, that is status1 to all of them.
Then you're selecting the select element that has an id of status1 like
var select = $('#status1'); //select #status1 option
Therefore, only the first select element will be selected.
EDIT:
Your question is not completely clear.
However, this is how you can add different Id for select inside each of your <td>
Replace this
rowNew.children().eq(5).html('<select class="status1" id="status1">');
With something like
rowNew.children().eq(5).html('<select class="status1" id="status'+key+'">');
So this will have different Ids.

Not able to pass the values from MVC(Razor) view to JsonResult method in Controller

I'm having two dropdown lists in my MVC(Razor) view: Country and State.
I'm able to fill both the dropdown's independent of each other.Now i want to fill second dropdown(State) based on the change event of Country's dropdown.
For this I have used JsonResult method in Controller and for this method i'm passing countryID on the Change event of Country from my view inorder to fill my second dropdown state.
Problem Statement: The JsonResult method is getting triggered from my view but the CountryId value is not getting passed from view to controller in-order to fill state.
What i'm doing wrong here?
View:
Javascript:
<script type="text/JavaScript">
function CountryChange() {
var url = '#Url.Content("~/MasterConfigGeneral/GetState")';
var ddlsource = "#CountryID";
var ddltarget = "#StateID";
if ($(ddlsource).val() != "") {
$.ajaxSetup({ cache: false });
$.getJSON(url, { countryID: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$("#StateID").append("<option value=''>Select State</option>");
$.each(data, function (index, optionData) {
$("#StateID").append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
else {
$("#StateID").empty();
$("#StateID").append("<option value=''>Select State</option>");
}
}
</script>
Dropdown's in my View:
<div class="cssclass">
#Html.DropDownListFor(model => model.companyModel.CountryID, new SelectList(Model.ddlCountryStateCity.ddlCountry, "Value", "Text"), "Select Country", new { onchange="CountryChange()" })
#Html.ValidationMessageFor(model => model.companyModel.CountryID)
</div>
<div class="cssclass">
#Html.LabelFor(model => model.companyModel.StateID)
</div>
<div class="editor-field">
#Html.DropDownList("stateid",Model.ddlCountryStateCity.ddlState,"Select State")
#Html.ValidationMessageFor(model => model.companyModel.StateID)
</div>
Controller:
Country Dropdown:
#region Country
public DropdownListCountryStateCity FillDropDownListCountry()
{
objDropDownCountryStateCity.ddlCountry = (from s in dbEntity.Countries
select new SelectListItem()
{
Text = s.Name,
Value = s.CountryID
}).ToList<SelectListItem>();
return objDropDownCountryStateCity;
}
#endregion
State Dropdown:
#region State
public JsonResult GetState(string countryID)
{
JsonResult jsResult = new JsonResult();
objDropDownCountryStateCity.ddlState = (from csc in dbEntity.CountryStateCities
join c in dbEntity.Countries on csc.CountryID equals c.CountryID
join s in dbEntity.States on csc.StateID equals s.StateID
where csc.CountryID == countryID
select new SelectListItem()
{
Text = s.Name,
Value = s.StateID
}).ToList<SelectListItem>();
jsResult.Data = objDropDownCountryStateCity.ddlState;
jsResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsResult;
}
#endregion
Your problem lies on how the DropDownListFor helper generates the element.
In your code, it's generating names and ids something like this:
<select id="companyModel_CountryID" name="companyModel.CountryID">
...
</select>
In your javascript the ddlSouce is "#CountryID". Since there's no element with that id, jQuery pass null as data to $.getJSON. That's why the controller method receives nothing.
You have two options:
Change ddlSource javascript to the proper id (you'll have to see on the source code) OR
Change the last DropDownListFor helper from
new { onchange="CountryChange()" }
to
new { id = "CountryID", onchange="CountryChange()" }
IMHO, the last option is the best choice.

How to get the values of Check Box(#Html.CheckBox) through JQuery JSON data

I want to bind values(checked or not) to a #Html.CheckBox in MVC 3 through JQuery.
This is my 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 />
}}
This is what I tried-
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"," ")**
In the above line, you are accessing the checkbox using ID, but if there are multiple checkboxes having the same ID, then it will work only for the first checkbox. So, add a class attribute to all the checkboxes and then access them using the class.
To make it work you can try as follows,
Create checkbox with the unique name as follows:
int counter = 0;
foreach (var item in Brands)
{
#Html.CheckBox("Brands" + counter, false, new{value = item.Value});
counter++;
}
It will create html markup somewhat similar like this:
<input type="checkbox" name = "Brands0" />
<input type="checkbox" name = "Brands1" />
<input type="checkbox" name = "Brands2" />
Then in jquery you can retrive the values like this:
for(int i=0;i<data.Configuration.OfficeBrands.count;i++)
{
$( "input[name*='"Brands"+i+"]"').attr('checked', data.Configuration.OfficeBrands[i]);
}
This is worked for me-
$.each(data.Configuration.OfficeBrands, function(i, brand) {
$(':checkbox[Value="' + brand.ID + '"]').prop('checked', true);});

Categories

Resources