Three Tables Cascading DropdownList in Asp.net MVC - javascript

I want to have a cascading dropdownlist in Asp.Net MVC. I have managed to do it with Two Tables Country and State, now I want to add City.
public class Country
{
[Key]
public int cId { get; set; }
public string cName { get; set; }
public ICollection<State> state { get; set; }
}
public class State
{
[Key]
public int sId { get; set; }
public string sname { get; set; }
public int cId { get; set; }
public Country country { get; set; }
}
//Get list of States
public JsonResult GetStateList(int cId)
{
db.Configuration.ProxyCreationEnabled = false;
List<State> listState = db.States.Where(x => x.cId == cId).ToList();
return Json(listState,JsonRequestBehavior.AllowGet);
}
//Script that invokes the Method
$(document).ready(function () {
$("#cId").change(function () {
$.get("/Home/GetStateList", { cId: $("#cId").val() }, function (data) {
$("#sId").empty();
$.each(data, function (index, row) {
$("#sId").append("<option value= '"+row.sId+"'>"+ row.sname+"</option>")
});
});
})
});

Well just add this:
public class City
{
[Key]
public int cityId { get; set; }
public string cityName { get; set; }
public int sId { get; set; } // stateId
public State state { get; set; }
}
public JsonResult GetCityList(int sId)
{
db.Configuration.ProxyCreationEnabled = false;
List<City> listCity = db.Cities.Where(x => x.sId == sId).ToList();
return Json(listCity,JsonRequestBehavior.AllowGet);
}
$(document).ready(function () {
$("#sId").change(function () {
$.get("/Home/GetCityList", { sId: $("#sId").val() }, function (data) {
$("#cityId").empty();
$.each(data, function (index, row) {
$("#cityId").append("<option value= '"+row.cityId+"'>"+ row.cityName+"</option>")
});
});
})
});

Related

How do i do crud from multiple tables in visual studio mvc

Hi new to visual studio and mvc in general and im trying to make a mvc crud including two tables. I have so far managed to do Create and List in index but i have having problem trying to edit,delete and show details.
Desc Class
[Table("klsm_InvoiceDesc")]
public class Desc
{
[Key]
public string InternalInvoiceNo { get; set; }
public string InvoiceNo { get; set; }
public int DescNo { get; set; }
public string Principal { get; set; }
public string ChargeCode { get; set; }
public string Quantity { get; set; }
public string Description { get; set; }
public string UnitPrice { get; set; }
public string Amount { get; set; }
public string ForeignAmount { get; set; }
public string EL1 { get; set; }
public string EL2 { get; set; }
public string ShortName { get; set; }
public string InvoiceType { get; set; }
public string PONumber { get; set; }
public string Batch { get; set; }
public string CCVBatch { get; set; }
public string PaidAmount { get; set; }
public string Paid { get; set; }
public string TT { get; set; }
public string BankCode { get; set; }
}
College Class
[Table("klsm_Invoice")]
public class College
{
[Key]
public string InternalInvoiceNo { get; set; }
public string InvoiceNo { get; set; }
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime InvoiceDate { get; set; }
public string CustomerName { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public decimal Amount { get; set; }
public decimal ForeignAmount { get; set; }
public string UserCreated { get; set; }
public string UserModified { get; set; }
public int AccMonth { get; set; }
public int AccYear { get; set; }
public string AccStatus { get; set; }
public string Status { get; set; }
public string PaidStatus { get; set; }
public string Principal { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
public string EL1 { get; set; }
public string InvoiceType { get; set; }
public string CurrencyType { get; set; }
public decimal ExchangeRate { get; set; }
public string GSTChecked { get; set; }
public DateTime PaymentSchedule { get; set; }
public string PaymentMode { get; set; }
public string CashAdvance { get; set; }
}
my home controller
public class HomeController : Controller
{
// GET: Home
DataContext db = new DataContext();
public ActionResult Index()
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice").ToList();
return View(data);
//List<College> klsm_Invoice = db.klsm_Invoice.ToList();
//return View(klsm_Invoice);
}
// GET: Home/Details/5
public ActionResult Details(string id)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id).SingleOrDefault();
return View(data);
}
// GET: Home/Edit/5
public ActionResult Edit(string id)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id).SingleOrDefault();
return View(data);
}
// POST: Home/Edit/5
[HttpPost]
public ActionResult Edit(string id, College collection)
{
db.Entry(collection).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
// GET: Home/Delete/5
public ActionResult Delete(string id)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id).SingleOrDefault();
return View(data);
}
// POST: Home/Delete/5
[HttpPost]
public ActionResult Delete(string id, College collection)
{
try
{
// TODO: Add delete logic here
int result = db.Database.ExecuteSqlCommand("DELETE FROM klsm_Invoice WHERE InternalInvoiceNo=#p0", id);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Search(string InternalInvoiceNo)
{
var data = db.klsm_Invoice.SqlQuery("SELECT * FROM klsm_Invoice WHERE InternalInvoiceNo = '" + InternalInvoiceNo + "' ").ToList();
return PartialView("DefaultIndex", data);
}
// GET: Home/Create
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult CreateInvoice(string invoiceDetailsList, string internalInvoiceNo, string invoiceNo, DateTime invoiceDate, string customerName, int year, int month, string amount, string foreignAmount, string userCreated, string userModified, int accMonth, int accYear, string accStatus, string status, string paidStatus, string principal, DateTime dateCreated, DateTime dateModified, string el1, string invoiceType, string currrencyType, string exchangeRate, string gstChecked, DateTime paymentSchedule, string paymentMode, string cashAdvance)
{
List<Desc> detailsList = JsonConvert.DeserializeObject<List<Desc>>(invoiceDetailsList);
var addingmaster = new College();
{
addingmaster.InternalInvoiceNo = internalInvoiceNo;
addingmaster.InvoiceNo = invoiceNo;
addingmaster.InvoiceDate = Convert.ToDateTime(invoiceDate);
addingmaster.CustomerName = customerName;
addingmaster.Year = year;
addingmaster.Month = month;
addingmaster.Amount = Convert.ToDecimal(amount);
addingmaster.ForeignAmount = Convert.ToDecimal(foreignAmount);
addingmaster.UserCreated = userCreated;
addingmaster.UserModified = userModified;
addingmaster.AccMonth = accMonth;
addingmaster.AccYear = accYear;
addingmaster.AccStatus = accStatus;
addingmaster.Status = status;
addingmaster.PaidStatus = paidStatus;
addingmaster.Principal = principal;
addingmaster.DateCreated = Convert.ToDateTime(dateCreated);
addingmaster.DateModified = Convert.ToDateTime(dateModified);
addingmaster.EL1 = el1;
addingmaster.InvoiceType = invoiceType;
addingmaster.CurrencyType = currrencyType;
addingmaster.ExchangeRate = Convert.ToDecimal(exchangeRate);
addingmaster.GSTChecked = gstChecked;
addingmaster.PaymentSchedule = Convert.ToDateTime(paymentSchedule);
addingmaster.PaymentMode = paymentMode;
addingmaster.CashAdvance = cashAdvance;
db.klsm_Invoice.Add(addingmaster);
db.SaveChanges();
}
foreach (var item in detailsList)
{
Desc addingdetails = new Desc();
addingdetails.InternalInvoiceNo = item.InternalInvoiceNo;
addingdetails.InvoiceNo = item.InvoiceNo;
addingdetails.DescNo = item.DescNo;
addingdetails.Principal = item.Principal;
addingdetails.ChargeCode = item.ChargeCode;
addingdetails.Quantity = item.Quantity;
addingdetails.Description = item.Description;
addingdetails.UnitPrice = item.UnitPrice;
addingdetails.Amount = item.Amount;
addingdetails.ForeignAmount = item.ForeignAmount;
addingdetails.EL1 = item.EL1;
addingdetails.EL2 = item.EL2;
addingdetails.ShortName = item.ShortName;
addingdetails.InvoiceType = item.InvoiceType;
addingdetails.PONumber = item.PONumber;
addingdetails.Batch = item.Batch;
addingdetails.CCVBatch = item.CCVBatch;
addingdetails.PaidAmount = item.PaidAmount;
addingdetails.Paid = item.Paid;
addingdetails.TT = item.TT;
addingdetails.BankCode = item.BankCode;
//addingdetails.Id = item.Id;
db.klsm_InvoiceDesc.Add(addingdetails);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
}
I have yet to add views for the needed help so anything will help rn

Passing a list from angular to c# through http request

My method in c# receives a list as a parameter, I am trying to call this method in angular by passing it an array, but the problem is that the info doesn't reach the c# method, the list is always empty, even though there was information in the angular array.
export class StationAllocationPostModel{
idAppDeviceOwnerEntity: number;
idAppDeviceOwnerEntityOriginal: number;
idAppDeviceOwnerEntityRentalLocationId: number;
Observations: string;
selectedAppDevices: StationAllocationModel[];
}
createNewStationAllocation(selectedAppDevices: StationAllocationPostModel){
return this.post("home/CreateAppDeviceRentalLocationAllocation", selectedAppDevices, {
params: {
'idAppDeviceOwnerEntity': selectedAppDevices.idAppDeviceOwnerEntity,
'idAppDeviceOwnerEntityRentalLocationId': selectedAppDevices.idAppDeviceOwnerEntityRentalLocationId,
'Observations': selectedAppDevices.Observations,
'selectedAppDevices': selectedAppDevices.selectedAppDevices
}
});
}
public post(url: string, data: any, options = null) {
return new Promise<any>((resolve, reject) => {
let response;
this.http.post(
this.baseUrl + url,
{
data: data
},
{
headers: options ? options.headers : null,
observe: options ? options.observe : null,
params: options ? options.params : null,
reportProgress: options ? options.reportProgress : null,
responseType: options ? options.responseType : null,
withCredentials: options ? options.withCredentials : null
}
)
.subscribe(
data => {
response = data;
if (response && !response.success) {
if (response.response.ServerResponse[0].MessageType == "NOSESSIONEXCEPTION") {
localStorage.removeItem('userSession');
this.router.navigate(['/login'], { queryParams: { returnUrl: this.router.url } });
}
}
},
error => {
resolve(null);
this.handleError(url, options ? options.params : null );
console.log(error);
}, () => {
if (response) {
resolve(response);
} else {
resolve(null);
}
}
);
})
}
This is my c# method:
public Object CreateAppDeviceRentalLocationAllocation(<other params>, List<AppDeviceRentalLocationAllocationHistoryExtended> selectedAppDevices)
{
...
}
I am expecting that the c# method receives a list with elements, but it always comes out empty for some reason. The 'other params' are getting the right information, so I don't know what's wrong with the list.
Sorry for the long post, I'm new here.
Could you please form a param object on the C# method that holds the following :
public class SelectedAppDevice
{
public int idAppDevice { get; set; }
public int idAppDeviceOwnerEntity { get; set; }
public int idAppDeviceOwnerEntityRentalLocationId { get; set; }
public string Observations { get; set; }
public string DeviceId { get; set; }
public string EntityRentalLocationName { get; set; }
public DateTime CreationDate { get; set; }
public DateTime EndDate { get; set; }
public string CreatedByUserName { get; set; }
public int RentalStatus { get; set; }
public int idAppDeviceRental { get; set; }
public bool IsRentalStart { get; set; }
public bool IsRentalEnd { get; set; }
public object idNextExpectedEntityRentalLocationName { get; set; }
public object NextExpectedEntityRentalLocationName { get; set; }
public string LastKnownEntityRentingId { get; set; }
public string CallerId { get; set; }
public int RentalStatusId { get; set; }
public int DeviceStatusId { get; set; }
}
public class Data
{
public string Observations { get; set; }
public int idAppDeviceOwnerEntityRentalLocationId { get; set; }
public int idAppDeviceOwnerEntity { get; set; }
public List<SelectedAppDevice> selectedAppDevices { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
and make it as a controller method parameter :
public Object CreateAppDeviceRentalLocationAllocation(RootObject param)
{
...
}

Have to show Model data into View using JavaScript MVC C#

I have page where I save user, contact and address details. The users could have multiple contact and address, So I have added the control to populate dynamically.
Form is working fine, except if any exception occurrs, the controller action return view with model.
This follows the structure of Model:
Model
public class UserModel
{
public UserDetail User { get; set; }
public IList<UserContact> Contact { get; set; }
public IList<UserAddress> Address { get; set; }
}
Contact Model :
public partial class UserContact
{
public int Id { get; set; }
public int UserId { get; set; }
public string ContactType { get; set; }
public string Mobile { get; set; }
public string Email { get; set; }
public bool IsActive { get; set; }
public virtual UserDetail UserDetail { get; set; }
}
Address Model
public partial class UserAddress
{
public int Id { get; set; }
public int UserId { get; set; }
public string AddressType { get; set; }
public string AddressName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostCode { get; set; }
public bool IsActive { get; set; }
public virtual UserDetail UserDetail { get; set; }
}
When value return, the following function suppose to check the Contact and Address and then then populate each record in dynamic created input section in view.
<script type="text/javascript">
$(document).ready(function () {
AddDynamicData();
function AddDynamicData() {
var valuesContacts = eval('#Html.Raw(Json.Encode(Model.Contact))');
var valuesAddresses = eval('#Html.Raw(Json.Encode(Model.Address))');
if (valuesContacts != null) {
var iContact = 0;
$(valuesContacts).each(function () {
$("#divContact").append(GetDynamicContact(iContact++, valuesContacts.contactType, valuesContacts.mobile, valuesContacts.email));
});
}
if (valuesAddresses != null) {
var iAddress = 0;
$(valuesAddresses).each(function () {
$("#divAddress").append(GetDynamicAddress(iAddress++, valuesAddresses.addressType, valuesAddresses.addressName, valuesAddresses.addressLine1, valuesAddresses.addressLine2, valuesAddresses.city, valuesAddresses.state, valuesAddresses.postCode));
});
}
}
</script>
The Function does not work properly, It does create the field but does not populate the user input data into textbox... Please advise how to fix the same and how to populate the records in view....
Added the View after submitting the form
<Update>
#Updated New Code with function & added screenshot
</Update>

When creating double dropdown SelectList with JQuery on POST returns 0. ASP.Net CORE 2.1

I have created two dropdownlists, of which one acts as a filter for the other. So, with dropdown Customer a customer is selected and only a limited set of ClientUsers is presented in in the dropdown ClientUser. I use a Jquery function to make this happen.
The selection works excellent, but when I POST the form the ClientUser is set to 0, instead of the choice.
The View is as follows (simplified for readability purposes):
#model DropDownTester2.Models.CaseViewModel
<form asp-action="Maak">
<label asp-for="CaseTitle" class="control-label"></label>
<input asp-for="CaseTitle" class="form-control" />
<select id="customerId" asp-for="CustomerId" asp-items='#(new SelectList(ViewBag.customers, "CustomerId", "CompanyName"))'>
<option>Select Customer Name</option>
</select>
<select id="clientUserId" asp-for="ClientUserId" asp-items='#(new SelectList(string.Empty, "ClientUserId", "LastName"))'>
</select>
<input type="submit" value="Maak" class="btn btn-default" />
</form>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#customerId").change(function () {
var url = '#Url.Content("~/")' + "Case/getClientUserById";
var ddlsource = "#customerId";
$.getJSON(url, { id: $(ddlsource).val() }, function (data) {
//$.getJSON("#Url.Action("getClientUserById","Case")", { id: $(ddlsource).val() }, function (data) {
var items = '';
$("#clientUserId").empty();
$.each(data, function (i, row) {
items += "<option value='" + row.value + "'>" + row.text + "</option>";
});
$("#clientUserId").html(items);
})
});
});
</script>
}
The CaseViewModel is:
public class CaseViewModel
{
public int CaseId { get; set; }
public string CaseTitle { get; set; }
public int CustomerId { get; set; }
public int ClientUserId { get; set; }
public IEnumerable<Customer> CustomerList { get; set; }
public IEnumerable<ClientUser> ClientUserList {get; set;}
My Model for Case is:
public class Case
{
public int CaseId { get; set; }
public string CaseTitle { get; set; }
public string CaseRoleDescription { get; set; }
public int CustomerId { get; set; }
public int ClientUserId { get; set; }
public virtual Customer Customer { get; set; }
public virtual ICollection<ClientUser> ClientUsers { get; set; }
}
Finally my controllers are :
// GET: Case/Maak
public IActionResult Maak()
{
ViewBag.customers = _context.Customer.ToList();
return View();
}
public JsonResult getClientUserById(int id)
{
List<ClientUser> list = new List<ClientUser>();
list = _context.ClientUser.Where(c => c.Customer.CustomerId == id).ToList();
list.Insert(0, new ClientUser { ClientUserId = 0, LastName = "Please select a clientuser" });
return Json(new SelectList(list, "ClientUserId", "LastName"));
}
// POST: Case/Maak
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Maak(CaseViewModel model)
{
if (ModelState.IsValid)
{
var newCase = new Case
{
CaseId = model.CaseId,
CaseTitle = model.CaseTitle,
CustomerId = model.CustomerId,
ClientUserId = model.ClientUserId
};
_context.Add(newCase);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["CustomerId"] = new SelectList(_context.Set<Customer>(), "CustomerId", "CustomerId", model.CustomerId);
return View(model);
}
I can't reproduce your issue :
The difference part of codes is that i create the Customer/ClientUser manually but that shouldn't be the issue cause :
public class Customer {
public int CustomerId { get; set; }
public string CompanyName { get; set; }
}
public class ClientUser
{
public int ClientUserId { get; set; }
public string LastName { get; set; }
}
You may search the "ClientUserId " in your pages to confirm whether other function reset the value .
As a workaround, you can also :
Create a hidden filed in your page and bind to your model property , create the select change event javascript function to set the value based on the selection .
Use Jquery to get the selected opinion , use Ajax to call action function and pass the value as parameter .

Json invoke not working after moving to mvc5

Same code stopped working after move to mvc5. In the following code I am trying to get cities for a country which is chosen in a dropdownlist using json.
The View.cshtml
#Html.DropDownList("CountryId", (SelectList)ViewBag.Countries, " -- choose a country -- ", new { onchange = "CountryDDLChanged()", #class = "form-control" })
JavaScript file (a part of the code)
function CountryDDLChanged() {
var url1 = "../Country/GetCitiesByCountryId";
var countryid = $("#CountryId").val();
$.ajax({
type: "GET",
url: url1,
data: { countryId: countryid },
dataType: "json",
success: function (result) {
alert("yes");
},
error: function(req, status, error){
alert(error);
}
});
}
CountryController
public JsonResult GetCitiesByCountryId(int countryId)
{
JsonResult result = new JsonResult();
using (var db = new DBContext())
{
List<City> cities = db.Cities.Where(c => c.CountryId == countryId).ToList();
result.Data = cities;
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
return result;
}
When I digg down in the code and debugging it. it generates this error.
he ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Why this works in MVC4 but not in MVC5? is it because of different version of EF?
how can I solve it?
UPDATED: Here is my Country Entithy and City :
[Table("Country")]
public class Country
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int CountryId { get; set; }
[StringLength(100)]
public string Name { get; set; }
public virtual List<City> Cities { get; set; }
public virtual List<Member> Members { get; set; }
public virtual List<MemberFee> MemberFees { get; set; }
}
[Table("City")]
public class City
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int CityId { get; set; }
public string Name { get; set; }
public int CountryId { get; set; }
[ForeignKey("CountryId")]
public virtual Country Country { get; set; }
public virtual List<Member> Members { get; set; }
}

Categories

Resources