Unable to clear the Multiselect dropdown and populate values in it dynamically - c#

I have made two multiselect dropdown using multiselect js plugin.
2nd dropdown gets populated on the option selection of 1st dropdown. I have use ajax for this purpose. But on ajax callback, 2nd dropdown elements are not getting clear, and new options are not populating.
This is my html code:
<div class="row col-md-6" >
<select id="multidropdown" multiple="multiple" onchange="ChangedView()">
#foreach (var item in clients)
{
<option value=#item.ToString() class="col-md-5"> #item.ToString() </option>
}
</select>
</div>
<div class="row col-md-6" id="ProgramsDiv">
<select id="programIDs" multiple="multiple" onchange="SelectSensorsFromPrograms()">
#foreach (var item in programs)
{
<option value=#item.ToString() class="col-md-5"> #item.ToString() </option>
}
</select>
</div>
and this is my JavaScript code:
function ChangedView()
{
$(".mtable").remove();
var multiclients = $("#multidropdown option:selected").text();
var program = $("#programIDs option:selected").text();
var sensors = $("#sensorIDs option:selected").text();
var request = $.ajax({
url: '#Url.Action("GetselectedProgramClient")',
type: 'POST',
data:
{
"ClientNames": multiclients
},
dataType: 'json',
success: function (data)
{
debugger;
if (data.length > 0)
{
$('#programIDs').html('');
var options = '';
console.log(data.length+"\n");
for (var i = 0; i < data.length; i++) {
options += '<option value="' + data[i] + '">' + data[i] +" " + '</option>';
console.log(options);
}
$('#programIDs').append(options);
$('#programIDs').multiselect('rebuild');
}
},
error: function (xhr) {
console.log("Error: " + xhr.statusText);
if (xhr.statusText == 'error') {
return;
}
else if (xhr.statusText == 'OK') {
return;
}
}
});
}

Related

Trying to create a cart Counter Variable

I am trying to create a counter variable where when a user clicks "Add To Cart" a number will appear indicating that the item was added and the number shown represents how many items are in the cart. My AddToCart controller can create a list and set it to a session variable. But I am having trouble setting the session variable without having to refresh the page. I believe it has something to do with my ajax. My main problem is that I don't know how to be able to access the new session variable so that the number next to the cart button updates when the add to cart button is pressed.
[HttpPost]
public JsonResult AddToCart(int ProductID)
{
Products productAccess = new Products();
List<ProductTier> HomeList = productAccess.IndexList();
CartAccess cartaccess = new CartAccess();
Cart product = cartaccess.FindProduct(ProductID);
product.Quantity = 1;
if (Session["cart"] == null)
{
List<Cart> ProductList = new List<Cart>();
ProductList.Add ( product );
Session["cart"] = ProductList;
Session["CartCounter"] = ProductList.Count;
}
else
{
List<Cart> Existingcart = (List<Cart>)Session["cart"];
int index = isExist(ProductID);
if (index != -1)
{
Existingcart[index].Quantity++;
}
else
{
Existingcart.Add(product);
}
Session["cart"] = Existingcart;
Session["CartCounter"] = Existingcart.Count;
}
return Json("Success");
}
function AddToCart(item) {
var ProductID = $(item).attr("ProductID");
var formData = new FormData();
formData.append("ProductID", ProductID);
$.ajax({
async: true,
type: 'POST',
contentType: false,
processData: false,
data: formData,
dataType: 'JSON',
url: '/Default/AddToCart',
success: function (data) {
if (data.sucess) {
$("#CartItem").text("Sucess Working : " + data);
window.alert("Success");
alert('Success Work');
}
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
}
<div style="text-align:right;width:30%;margin-right:10px">
<input type="button" name="AddToCart" value="Add To Cart" class="btn btn-info" ProductID="#item.ProductID" onclick="AddToCart(this)">
</div>
<ul class="navbar-nav ml-auto">
<li class="nav-item ml-auto" style="margin-left:auto;">
#if (Session["CartCounter"] == null)
{
#Html.ActionLink("Cart", "Checkout", "DefaultController", new { #class = "nav-link", id = "CartItem" })
}
else
{
#Html.ActionLink("Cart(" + Session["CartCounter"] + ")", "Checkout", "DefaultController", new { #class = "nav-link" , id = "CartItem" })
}
</li>
</ul>
I am still new to MVC and am learning new methods, Please give me any tips I would appreciate it.

Dropdown list onchange can't display dropdown list

I have 2 dropdown. States/Divisions and Townships. Townships dropdown is blank. If I choose something in the S/D dropdown, Township dropdown changes according to the S/D selection. But I can't see the dropdown list in the Township and it's just white. Can someone help me please?
It's work but the changes in township dropdown list are blank.
My controller
[HttpGet]
public JsonResult Township_Filter(string id)
{
List<string> tsp = db.TB_Township.Where(t => t.StateDivisionID.Equals(id)).Select(t => t.Township).ToList();
return Json(tsp, JsonRequestBehavior.AllowGet);
}
My Ajax call
$(document).ready(function () {
$("#StateDivision").on("change", function () {
var sdID = $("#StateDivision").val();
$.ajax({
type: 'GET',
url: '/LoanMaster/Township_Filter',
data: {id : sdID},
beforeSend: function(){
},
success: function (tsp) {
if(tsp != null)
{
$('#Township').empty();
$('#Township').append($('<option value="">--Choose--</option>'));
for (i = 0; i < tsp.length; i++)
{
$('#Township').append($('<option value="' + tsp[i] + '>"' + tsp[i] + '</option>'));
}
}
},
complete: function () {
}
});
});
});
My View
<select id="StateDivision" class="form-control">
<option>--Choose--</option>
<option value="100">A</option>
<option value="101">B</option>
</select>
<select id="Township" class="form-control abc">
<option>--Choose--</option>
</select>
There is a syntax error
$('<option value="' + tsp[i] + '>" ' + tsp[i] + '</option>')
maybe that's why. try This
$('<option value="' + tsp[i] + '">' + tsp[i] + '</option>')

How to access an array retrieved from controller via AJAX

I call an MVC controller via Java and AJAX. The data goes to the controller, the controller returns a List. How do I access that list? This may seem trivial, but I can't find it anywhere on google or SO. Most of the examples I've found call for using:
...
success: function (r) {
var exemptions = r.d;
...
for (var i = 0; i < exemptions.length; i++){
ddlist.appent('<option>' + exemptions[i] + '</option>');
....
}
That method, however, results in this error:
Uncaught TypeError: Cannot read property 'length' of undefined
at Object.success (6:281)
at u (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
Controller Method:
public JsonResult GetValidRecords(int year)
{
var items = new List<SelectListItem>();
var Exemptions = model.Permits.Where(m => m.Year == year).OrderBy(m => m.Exemption).OrderBy(m => m.Year).ToList();
foreach (Permit x in Exemptions)
{
items.Insert(items.Count, new SelectListItem { Text = x.Exemption.ToString(), Value = x.Exemption.ToString() });
}
return Json(items, JsonRequestBehavior.AllowGet);
}
The dropdown box:
<text>EXEMPTION RENEWAL FORM</text>
<select id="dd" name="dd" onchange="CallRenewalReport(this.value)">
<option value="">Select Year First</option>
</select>
#Html.DropDownList("ddldate", new SelectList(Model.RYearList, "ID", "Year", "Select a year"), new { #onchange = "GetGoodRecords(this.value)", #AppendDataBoundItems = "False" })
break;
The JavaScript/AJAX query:
<script type="text/javascript">
function GetGoodRecords(val) {
alert(val);
var year = val;
var RootUrl = '#Url.Content("~/")';
$.ajax({
url: RootUrl + "Reports/GetValidRecords",
data: { year: year },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var exemptions = response.d;
var ddlist = $('#dd');
ddlist.empty().append('<option selected="selected" value="0">Select Exemption</option>');
for (var i = 0; i < exemptions.length; i++) {
ddlist.append('<option>' + exemptions[i] + '</option>');
}
}
});
};
</script>
Can anyone spell this out to me in layman's terms?
Regards,
Carthax
Give this a shot in your success function:
success: function (response) {
for (var i = 0; i < response.length; i++) {
var obj = JSON.parse(JSON.stringify(response[i]));
alert(obj.Text);
}
}
This will show an alert of what is contained in each object of the response array.
(In case someone happens upon this question in google)
Based on input from #MikeMarshall, here is the solution that works:
The controller action is correct, but I'm putting it all in one place so you don't have to copy-and-paste from all over the page
public JsonResult GetValidRecords(int year)
{
var items = new List<SelectListItem>();
var Exemptions = model.Permits.Where(m => m.Year == year).OrderBy(m => m.Exemption).OrderBy(m => m.Year).ToList();
foreach (Permit x in Exemptions)
{
items.Insert(items.Count, new SelectListItem { Text = x.Exemption.ToString(), Value = x.Exemption.ToString() });
}
return Json(items, JsonRequestBehavior.AllowGet);
}
The razor code:
<text>EXEMPTION RENEWAL FORM</text>
<select id="dd" name="dd" onchange="CallRenewalReport(this.value)">
<option value="">Select Year First</option>
</select>
#Html.DropDownList("ddldate", new SelectList(Model.RYearList, "ID", "Year", "Select a year"), new { #onchange = "GetRecords(this.value)", #AppendDataBoundItems = "False" })
break;
The script:
<script type="text/javascript">
function GetRecords(val) {
alert(val);
var year = val;
var RootUrl = '#Url.Content("~/")';
$.ajax({
url: RootUrl + "Reports/GetValidRecords",
data: { year: year },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// get the dropdownlist
var ddlist = $('#dd');
// empty the dropdownlist and add "Select Exemption"
ddlist.empty().append('<option selected="selected" value="0">Select Exemption</option>');
// for each value in the response
for (var i = 0; i < response.length; i++) {
// properly query the Value and Text fields in the array
ddlist.append('<option value="' + response[i].Value + '">' + response[i].Text + '</option>');
}
}
});
};
</script>

Get selectedIndex of dropdown using c# (Razor)

Is it possible to get the selectedIndex of a dropdown in a view using C# (Razor). For example, can I fill a second dropdown based off the selectedIndex of another dropdown using Razor?
#model ViewModel
<select id="dropdown1">
//Options
</select>
<select id="dropdown2">
//Options
</select>
#if(//The selectedIndex of dropdown1 == 4)
{
//Fill dropdown 2 from model
}
When using Javascript, I am a little off as well:
<script>
if (dropdown1.selectedIndex === 3)
{
#foreach (var item in Model)
{
}
}
</script>
You can do it using a ajax call when the first dropdown changes:
<script type="text/javascript">
function getDropDown2Data(id) {
$.ajax({
url: '#Url.Action("GetDropDown2Data", "YourController")',
data: { Id: id },
dataType: "json",
type: "POST",
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Name + "\">" + item.Id + "</option>";
});
$("#dropDown2").html(items);
}
});
}
$(document).ready(function () {
$("#dropDown2").change(function () {
var id = $("#dropDown2").val();
getDropDown2Data(id);
});
});
</script>
#Html.DropDownListFor(x => x.Id, new SelectList(Model.Model1, "Id", "Name"), "Select")
#Html.DropDownListFor(x => x.Id, new SelectList(Model.Model2, "Id", "Name"), "Select")
And you action:
[HttpPost]
public ActionResult GetDropDown2Data(id id)
{
//Here you get your data, ie Model2
return Json(Model2, JsonRequestBehavior.AllowGet);
}

drop down list refresh in razor

I have a drop down list which represent states and according to selected state, I need to refresh City drop down list which represent the cities in the selected state. How can I refresh the city drop down ?
Here is my code :
public class AccountController : Controller
{
public static List<SelectListItem> StateListItem()
{
var stateList = new List<SeraydarBL.Accounts.State>();
var selectListItems = new List<SelectListItem>();
stateList = SeraydarBL.Accounts.SelectStates();
foreach (var state in stateList)
{
var selectListItem = new SelectListItem();
selectListItem.Text = state.name;
selectListItem.Value = state.id.ToString();
selectListItems.Add(selectListItem);
}
return selectListItems;
}
}
here is the razor :
#using (Html.BeginForm())
{
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
//-------------------------------------------------------
var stateList = new List<SelectListItem>();
stateList = AccountController.StateListItem();
}
#Html.LabelFor(model => model.StateId)
#Html.DropDownListFor(model => model.StateId, stateList, " Select your State ...")
#Html.ValidationMessageFor(m => m.StateId)
#*HERE MUST BE THE DROP DOWN LIST OF CITIES*#
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
<script>
$('#StateId').change(function () {
});
</script>
}
You can achieve this using jquery ajax call.
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#StateId").change(function () {
$("#CityId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'json',
data: { id: $("#StateId").val() },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityId").append('<option value="' + city.Value + '">' +``});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
refer few articles
http://www.codeproject.com/Articles/730953/Cascading-Dropdown-List-With-MVC-LINQ-to-SQL-and-A
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/

Categories