Update Cascading Dropdown in Mvc5 - sql

Hi i want to know how to update or edit cascading dropdown like (Country,state,City)in mvc5.I have created 3 cascading dropdowns Country State city.If i select Country State will append in state dropdownn like wise city. Now i save these 3 dropdown values in table successfully. But now i stuck with edit option. I donno how to bind the saved value to these dropdowns in edit from.
My model
public class UCustomerManagementViewModel
{
public string UCountry { get; set; }
public string UState { get; set; }
public string UCity { get; set; }
}
My Controller code
public JsonResult GetCountries()
{
var Countries = db.Countries.ToList();
return Json(Countries, JsonRequestBehavior.AllowGet);
}
public JsonResult GetStatesByCountryID(string countryId)
{
int id = Convert.ToInt32(countryId);
var states = db.States.Where(d => d.CountryID == id).Select(e => new { e.UID, e.StateName }).ToList();
return Json(states, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCityByStateID(string stateId)
{
int id = Convert.ToInt32(stateId);
var Cities = db.Cities.Where(d => d.StateID == id).Select(e => new { e.UID, e.CityName }).ToList();
return Json(Cities, JsonRequestBehavior.AllowGet);
}
public ActionResult Update(int id)
{
CustomerManagement cc = db.CustomerManagements.Find(id);
ViewBag.CountryID = new SelectList(db.Countries.Where(d => d.CountryID.ToString() == cc.Country.ToString()), "CountryID", "CountryName",cc.CountryID);
var ucusmanvm = new UCustomerManagementViewModel();
ucusmanvm.UCountry = cc.Country;(here i get value 1)
ucusmanvm.UState = cc.State;(here i get value 2)
ucusmanvm.UCity = cc.City;(here iget value 2)
return View(ucusmanvm);
}
here i pass all the value to view form
My View Code
$(document).ready(function () {
debugger;
$.ajax({
type: "GET",
url: '#Url.Action("GetCountries", "FrmCustomerManagement")',
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCountry').append('<option value="' + value.CountryID + '">' + value.CountryName + '</option>');
});
}
});
$('#dropdownCountry').change(function () {
debugger;
$('#dropdownState').empty();
var cval = $('#dropdownCountry').val()
$.ajax({
type: "POST",
url: '#Url.Action("GetStatesByCountryID", "FrmCustomerManagement")',
datatype: "Json",
data: { countryId: cval },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownState').append('<option value="' + value.UID + '">' + value.StateName + '</option>');
});
}
})
});
$('#dropdownState').change(function () {
debugger;
$('#dropdownCity').empty();
var sval = $('#dropdownState').val()
$.ajax({
type: "POST",
url: '#Url.Action("GetCityByStateID", "FrmCustomerManagement")',
datatype: "Json",
data: { stateId: sval },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCity').append('<option value="' + value.UID + '">' + value.CityName + '</option>');
});
}
})
});
#Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "Value", "Text"), "Please select a country", new { #class = "form-control", #width = "80%", #value=Model.UCountry})
<div class="col-sm-8">
<label>State</label>
#Html.DropDownList("dropdownState", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { #class = "form-control", #width = "80%" , #value=Model.UState})
</div>
<div class="col-sm-8">
<label>City</label>
#Html.DropDownList("dropdownCity", new SelectList(string.Empty, "Value", "Text"), "Please select a City", new { #class = "form-control", #width = "80%" , #value=Model.Ucity})
</div>
Here in update from also i acheive Cascading dropdown using ajax. but in update form i donno how to bring the save value to drop downs(Country city, state) from controller to view (eg i saved UAE in Country Dropdown but in edit mode i donno how to bring UAE value in Country dropdown ).I passed value from controller but i donno how to bind that value in view.please any one help me to resolve this issue .

Related

Send back FullCalendar events to .NET with AJAX

I would like to sendback FullCalendar events to .NET with an AJAX request. I create a custom button for that :
#{
ViewData["Title"] = "Planning visites";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>#ViewData["Title"]</h1>
<div id='calendar'></div>
#section scripts
{
<script>
let date = new Date();
let month = String(date.getMonth() + 1).padStart(2, '0');
let day = String(date.getDate()).padStart(2, '0');
let year = date.getFullYear();
let dateDuJour = year + '-' + month + '-' + day;
let dateDuJourplusunan = (year + 1) + '-' + month + '-' + day;
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
//themeSystem: 'bootstrap5',
//plugins: [ timeGridPlugin ],
initialView: 'timeGridWeek',
selectable: true,
selectOverlap: false,
//selectMirror: true,
validRange: {
start: dateDuJour,
end: dateDuJourplusunan
},
customButtons: {
enregistrermodifs: {
text: 'enregistrer',
click: function() {
var eventsobj = calendar.getEvents();
var data = JSON.stringify(eventsobj);
//var data = JSON.serialize(eventsobj);
alert(data);
$.ajax({
type: 'POST',
url: '#Url.Action("MAJAgenda","Agenda")',
//contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // when we use .serialize() this generates the data in query string format. this needs the default contentType (default content type is: contentType: 'application/x-www-form-urlencoded; charset=UTF-8') so it is optional, you can remove it
contentType: 'application/json; charset=utf-8',
data: data,
success: function(result) {
alert('Successfully received Data ');
console.log(result);
},
error: function() {
alert('Erreur : enregistrement non effectué');
console.log('Failed');
}
});
}
}
},
headerToolbar: {
left: 'prev,next,today,enregistrermodifs',
center: 'title',
right: 'dayGridMonth,timeGridWeek,dayGridDay'
},
buttonText: {
today: 'Aujourdhui',
month: 'mois',
week: 'semaine',
timeGridWeek: 'jour',
day: 'jour',
list: 'liste'
},
initialDate: dateDuJour,
navLinks: true, // can click day/week names to navigate views
editable: true,
dayMaxEvents: true, // allow "more" link when too many events
events:'#Url.Action("RecupDonneesAgenda","Agenda")?annonceId=#ViewBag.AnnonceId',
select: function(info) {
calendar.addEvent({
//id: info.startStr,
title: 'Indisponibilité',
start: info.startStr,
end: info.endStr,
allDay: false
});
},
eventClick: function(info) {
var eventobj = info.event;
eventobj.remove();
}
});
calendar.render();
calendar.setOption('locale', 'fr');
});
</script>
}
Here's my model in .NET :
public class AgendaAJAX
{
public string? title { get; set; }
public DateTime? start { get; set; }
public DateTime? end { get; set; }
}
And here's my action method :
[HttpPost]
public async Task<IActionResult> MAJAgenda(AgendaAJAX? agenda)
{
string userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
////List<Agenda> agenda = await _context.Agendas.Where(a => a.AnnonceID == annonceId && a.Personne1 == userID).ToListAsync();
//JsonResult result = new JsonResult(agenda);
return View("Agenda");
}
THE AJAX call works well : here's the JSON data :
[{"title":"Indisponibilité","start":"2022-06-09T07:30:00+02:00","end":"2022-06-09T12:30:00+02:00"},{"title":"Indisponibilité","start":"2022-06-10T10:00:00+02:00","end":"2022-06-10T15:00:00+02:00"},{"title":"Indisponibilité","start":"2022-06-11T07:00:00+02:00","end":"2022-06-11T09:30:00+02:00"}]
The problem is that I don't receive any data in the action method : agenda remains null.
I don't understand why.
If you can help me please.
Thanks.

ASP.NET CORE MVC With Google Charts - No Data

Trying to implement Google Chart with ASP.Net CORE MVC.
Been at it for two days, but I can not figure out my mistake. I don't get an error, and I can see the array in the console, but no data.
VIEWMODEL
public class ZipCodes
{
public string ZipCode { get; set; }
public int ZipCount { get; set; }
}
CONTROLLER
public ActionResult IncidentsByZipCode()
{
var incidentsByZipCode = (from o in _context.Incident
group o by o.ZipCode into g
orderby g.Count() descending
select new
{
ZipCode = g.Key,
ZipCount = g.Count()
}).ToList();
return Json(incidentsByZipCode);
}
VIEW
function IncidentsByZipCode() {
$.ajax({
type: 'GET',
url: '#Url.Action("IncidentsByZipCode", "Controller")',
success: function (response) {
console.log(response);
var data = new google.visualization.DataTable();
data.addColumn('string', 'ZipCode');
data.addColumn('number', 'ZipCount');
for (var i = 0; i < response.result.length; i++) {
data.addRow([response.result[i].ZipCode, response.result[i].ZipCount]);
}
var chart = new google.visualization.ColumnChart(document.getElementById('incidentsByZipCode'));
chart.draw(data,
{
title: "",
position: "top",
fontsize: "14px",
chartArea: { width: '100%' },
});
},
error: function () {
alert("Error loading data!");
}
});
}
Because the api you use is not Column Chart, the data cannot be added and rendered correctly. According to the official example, you need to make some changes.
Here is the ajax code.
<script>
//Generate random colors
function bg() {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ',' + g + ',' + b + ")";
}
function IncidentsByZipCode() {
$.ajax({
type: 'GET',
url: '#Url.Action("IncidentsByZipCode","home")',
success: function (response) {
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
var obj = [
["Element", "Density", { role: "style" }],
];
$.each(response, function (index, value) {
obj.push([value.zipCode, value.zipCount, bg()])
})
var data = google.visualization.arrayToDataTable(obj);//This is method of Column Chart
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2]);
var chart = new google.visualization.ColumnChart(document.getElementById('incidentsByZipCode'));
chart.draw(data,
{
title: "",
position: "top",
fontsize: "14px",
chartArea: { width: '100%' },
});
}
},
error: function () {
alert("Error loading data!");
}
});
}
IncidentsByZipCode()
This is the controller.
public ActionResult IncidentsByZipCode()
{
//var incidentsByZipCode = (from o in _context.Incident
// group o by o.ZipCode into g
// orderby g.Count() descending
// select new
// {
// ZipCode = g.Key,
// ZipCount = g.Count()
// }).ToList();
var incidentsByZipCode = new List<ZipCodes>
{
new ZipCodes{ ZipCode="code1", ZipCount=3},
new ZipCodes{ZipCode="code2",ZipCount=4},
new ZipCodes{ZipCode="code3",ZipCount=2},
new ZipCodes{ZipCode="code4",ZipCount=9},
};
return Json(incidentsByZipCode);
}
Result, and you can also refer to this document
.

How to pass 2 parameters through $.getJson in MVC?

I am doing my application in MVC. I did cascading dropdownlist in list . While selecting the value from dropdown i passed the value by $.getJson() to the controller. I am passing one id to the controller. My problem is i need to pass 2 id's to the controller. Is it possible to send 2 ids to the controller?
My View page is
<div>
#Html.DropDownList("Business", ViewBag.CategoryID as SelectList ,"Select the Business Category", new { id = "Business" })
</div>
<div>
<label>Select the Service Type</label>
#*<select id="Buname" name="buname" style="width:150px"></select>*#
#Html.DropDownList("Service", ViewBag.Service as SelectList,"Select", new { id = "Service", name ="buname"})
</div>
<div>
<label> Select the Location</label>
<select id="Location" name="location" style="width:150px"></select>
</div>
<div>
<label> Select the Location</label>
<select id="Employee" name="employee" style="width:150px"></select>
</div>
<script type="text/javascript">
$(function () {
$('#Business').change(function () {
$.getJSON('/Appt/Categories/' + $('#Business').val(), function (data) {
var items = '<option> Any Hospital</option>'
$.each(data, function (i, Service) {
debugger;
items += "<option value='" + Service.Value + "'>" + Service.Text +
"</option>";
});
$("#Service").html(items);
});
});
$('#Service').change(function () {
$.getJSON('/Appt/Location/' + $('#Service').val(), function (data) {
var items = '<option> Any Location </option>';
$.each(data, function (i, location) {
items += "<option value='" + location.Value + "'>" + location.Text +
"</option>";
});
$("#Location").html(items);
});
});
$('#Location').change(function () {
$.getJSON('/Appt/Employee/' + $('#Location').val(), function (data) {
var items = '<option> Any Employee </option>';
$.each(data, function (i, employee) {
items += "<option value='" + employee.Value + "'>" + employee.Text +
"</option>";
});
$("#Employee").html(items);
$("Service").html(items);
});
});
});
</script>
My Controller code is
public ActionResult WaitingList()
{
SYTEntities ca = new SYTEntities();
ViewBag.CategoryId = new SelectList(ca.BusinessCategories.ToList(), "CategoryId", "CategoryName");
ViewBag.Service = new SelectList(ca.tblBusinessCategories.ToList(), "BusinessID", "BusinessName");
return View();
}
public JsonResult Categories(int id)
{
SYTEntities db = new SYTEntities();
var business = from s in db.tblBusinessCategories
where s.CategoryId == id
select s;
return Json(new SelectList(business.ToArray(),"BusinessID", "BusinessName"), JsonRequestBehavior.AllowGet);
}
public JsonResult Location(int id)
{
SYTEntities db = new SYTEntities();
var location = from s in db.tblBusinessLocations
where s.BusinessID == id
join loc in db.tblLocations
on s.LocID equals loc.LocationId
select loc;
return Json(new SelectList(location.ToArray(), "LocationId", "LocationName"), JsonRequestBehavior.AllowGet);
}
public JsonResult Employee(int id)
{
SYTEntities db = new SYTEntities();
var emp = from s in db.Employees
where s.LocationId == id && s.BusinessID == 91
select s;
return Json(new SelectList(emp.ToArray(), "EmpId", "EmpName"), JsonRequestBehavior.AllowGet);
}
In public JsonResult Employee(int id) i need to pass ('#Service') value.
Is it possible to do? Can anyone please help me?
You can pass as many values as you want using the data parameter of jQuery.getJSON
var url = '#Url.Action("Categories", "Appt")'; // don't hard code your urls!
$.getJSON(url, { id: $('#Business').val(), otherProperty: anotherValue }, function (data) {
Yes you just need to add one more parameter to the Controller Action as below.
public JsonResult Categories(int id, int id2)
{
SYTEntities db = new SYTEntities();
var business = from s in db.tblBusinessCategories
where s.CategoryId == id
select s;
return Json(new SelectList(business.ToArray(),"BusinessID", "BusinessName"), JsonRequestBehavior.AllowGet);
}
and the below change in you View
$.getJSON('/Appt/Categories/' + $('#Business').val(), { id2: ('#otherId2').val() }, function (data) {
var items = '<option> Any Hospital</option>'
$.each(data, function (i, Service) {
debugger;
items += "<option value='" + Service.Value + "'>" + Service.Text +
"</option>";
});
$("#Service").html(items);
});

Bind KendoUi dropdownlist

I want to filter ProductData dropdownlist below on load based on ViewBag value letsay ViewBag.Category. The viewbag value i need to pass to GetProductData(). How i can achieve this. Thank you
$("#ProductData").kendoDropDownList({
dataTextField: "OptionName",
dataValueField: "OptionID",
optionLabel: {
OptionName: "Please Select",
OptionID: ""
},
dataSource: {
transport: { read: { url: '#(Url.Content("~/ProductDetails/GetProductData"))'} }
}
});
<input type="ProductData" id="ProductData" name="ProductData" required validationMessage="Please select a product" style="width:110px; font-size:11px; margin-left:12px"/><span class="k-invalid-msg" data-for="ProductData"></span>
controller:
//Need to filter based on viewbag.category value
public JsonResult GetProductData()
{
var productList = new TREntities();
string Role = ViewBag.Role;
return Json(productList .ConfigOptions.Select(c => new { OptionID = c.OptionID, OptionName = c.OptionName, OptionDetails = c.OptionDetails, OptionTypeID = c.ConfigTypeID })
.OrderBy(c => c.OptionName).Where(e => e.OptionID == 33), JsonRequestBehavior.AllowGet);
}
transport:{ read: {
dataType: "json",
url: "ProductDetails/GetProductData",
data: getTestData
}}
function getTestData()
{
return {testID: parameterToSent} // you can take parameterToSent from where you want
};
public JsonResult GetProductData(string testID)
{
...
}

Get dropdown value and text in controller mvc4 razor

I am working on MVC4 project. I have form where dropdownlist is populated with text and value field.
#Html.DropDownList("SourceDropDownList", new SelectList(""), "-Select-", new { #class = "validate[required]" })
This dropdown is populated from other dropdown change event
here is that code
function OnSourceFacilityDropDownChange(source, e) {
$("#SourceDropDownList").empty();
var curOpt = new Option('-Select-', "");
$("#SourceDropDownList").get(0).options[$("#SourceDropDownList").get(0).options.length] = curOpt;
if (source.value != '') {
var url = getUrl() + '/AdminPanel/GetIns/?id=' + Math.random();
$.ajax({
url: url,
data: { clientid: $("#SourceDropDown").val(), strFacility: source.value }, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function (data) {
$.each(data, function (index, item) {
var curOpt = new Option(item.T, item.T);
curOpt.setAttribute("title", item.T);
$("#SourceDropDownList").get(0).options[$("#SourceDropDownList").get(0).options.length] = curOpt;
});
},
error: function (request, status, error) { alert("Status: " + status + "\n Exception Handling : \n" + request.responseText); },
complete: function () {
$("#divLoading").hide();
}
});
}
else {
}
}
and code in AdminPanel/GetIns controller is
public JsonResult GetInspection(int clientid, string strFacility)
{
var objlist = (from d in Context.tbl_insp
orderby d.str_insp ascending
where d.clientid.Equals(ClientId))
select new { T= d.str_inspname, V= d.dte_start.Value.ToShortDateString()}).ToArray();
Array InspectionList = objlist;
return Json(InspectionList, JsonRequestBehavior.AllowGet);
}
And in model class i have initialized the property of dropdown
public string SourceDropDownList{ get; set; }
now i am getting only text values of what i select in SourceDropDownList dropdown..
How do i get the value also ??
Try with this,Just Example
View
#Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")
#Html.DropDownList("CustomerNameId", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")
Script
<script type="text/javascript">
$(document).ready(function () {
$("#CustomerId").change(function () {
var Id = $("#CustomerId").val();
$.ajax({
url: '#Url.Action("GetCustomerNameWithId", "Test")',
type: "Post",
data: { CustomerNameId: Id },
success: function (listItems) {
var STSelectBox = jQuery('#CustomerNameId');
STSelectBox.empty();
if (listItems.length > 0) {
for (var i = 0; i < listItems.length; i++) {
if (i == 0) {
STSelectBox.append('<option value="' + i + '">--Select--</option>');
}
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
else {
for (var i = 0; i < listItems.length; i++) {
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
}
});
});
});
</script>
Controller
public JsonResult GetCustomerNameWithId(string CustomerNameId)
{
int _CustomerNameId = 0;
int.TryParse(CustomerNameId, out _CustomerNameId);
var listItems = GetCustomerNameId(_CustomerNameId).Select(s => new SelectListItem { Value = s.CID.ToString(), Text = s.CustomerName }).ToList<SelectListItem>();
return Json(listItems, JsonRequestBehavior.AllowGet);
}
Model
public class CustomerModel
{
public int CustomerId { get; set; }
public int CustomerNameId { get; set; }
}