Cascading (Dependent) DropDownList using ASP.NET MVC - c#

I have implemented Cascading (Dependent) DropDownList using ASP.NET MVC.
This is the tutorial
Now I need show alert message box after insert data and redirect on Index page in ASP.NET MVC.
To show alert message in ASP.NET MVC after insert data using store procedure from MySQL database, I have write the code like as shown below.
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
if (msg > 0)
{
alert("User Details Inserted Successfully");
window.location.href = "#Url.Action("Index", "Home")";
}
});
</script>
The data is correctly registered in the database table and the alert message box after insert data it's show.
But the redirect to index.cshtml not working because all the DropDownList on the form are empty except the first DropDownList that populates correctly.
window.location.href = "#Url.Action("Index", "Home")";
I mean that all other (populated cascading) DropDownList are enabled but empty.
I need redirect to Index Action page and being able to reload a new record, with this redirection it is impossible because the populated cascading DropDownList remain empty... instead of disabled and populated from value of first dropdownlist...
How to do resolve this?
Thanks.
Update 2021-01-02
#section Scripts {
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/DatePicker.js");
#Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
console.log(msg);
if (msg > 0)
{
alert("User Details Inserted Successfully");
var url = "#Url.Action("Index", "Home")";
window.location.href = url;
}
});
</script>
<script src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var ok = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
ok = false;
}
return ok;
});
$("#thedate").datepicker(options);
$(function () {
$(".loading").hide();
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#TicketId");
DisableDropDown("#CityId");
dropDownId = "#TicketId";
list = response.Ticket;
PopulateDropDown("#TicketId", list);
break;
case "TicketId":
list = response.States;
DisableDropDown("#StateId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", list);
dropDownId = "#CityId2";
list = response.Cities2;
PopulateDropDown("#CityId2", list);
$("#GPS").val(response.GPS);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option selected="selected" value="">[ === Select === ]</option>');
}
function PopulateDropDown(dropDownId, list) {
var modal = $('<div />');
modal.addClass("modalBackground");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
setTimeout(function () {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
$(".loading").hide();
$('.modalBackground').remove();
}
}, 1000);
}
</script>
}
update controller
[HttpPost]
public ActionResult Index(PersonModel person)
{
MTsqlinsert(person); //Insert values in the database
if (ModelState.IsValid)
{
PersonModel personModel = new PersonModel();
person.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
person.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + countryId, "StateName", "StateId");
person.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + stateId, "CityName", "CityID");
ViewData["result"] = "1";
return RedirectToAction("Index");
}
return View(person);
}
[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult Index()
{
PersonModel personModel = new PersonModel
{
Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
};
return View(personModel);
}

Related

Linq get data on load more button is click with start index and end index

i am using webApi and linq to get the data from SQL,Now i have Load More button in my page, when i click, it should bring 20 records each time,i am using has Start Index and End Index has my table column ID which is primary Key,when i click the load More Button, i ll get the last Id means last data ID from the list view, i am using that Id has my start index,now my problem is when i click on load more it brings 20 data but previous data has be erased, i need to get 20+20=40 data when i click my load more button for first time,how to achieve this.
//Linq//
public dynamic getALlImage(int userID, int LastImageID)
{
//here LastImageId is my Listview Last data ImageID
if (LastImageID!=0)
{
startIndex= LastImageID+20;
EndIndex=LastImageID-20;
}
else
{
startIndex= 20;
EndIndex=0;
}
GetAllListFields = (from user in dbContext.UserTable
join img in dbContext.ImageTable on user.userId equals img.userID into UserVoice
from Image in UserVoice.DefaultIfEmpty()
where (Image.imgId <= startIndex && Image.imgId >= EndIndex && Image.userID == userID && Image.IsStatusChecked == false)
orderby feeds.CreatedAt descending
select new
{
PostImage = Image == null ? 0 : Image.ImageID,
Image = usrMessae==null?0: Image.userMessage,
createdAt = feeds == null ? DateTime.UtcNow : feeds.CreatedAt,
UserId = userdata == null ? 0 : userdata.userId,
Name = userdata == null ? " " : userdata.Name,
username = userdata == null ? " " : userdata.userName,
Email = userdata == null ? " " : userdata.emailID,
}).Distinct().OrderByDescending(x => x.createdAt).Take(startIndex).ToList();
}
//HTML//
<div data-role="view">
<div>
<ul data-role="listview" data-bind="foreach:ImageList">
<li>
<div data-bind="text:userID"></div>
<div data-bind="text:userName"></div>
<div data-bind="text:UserImageSrc"></div>
<div data-bind="text:ImageId></div>
<div data-bind="text:PostImageSrc"></div>
<div >
<button data-bind="click:getLoadMoreImageData">Load More</button>
</div>
</li>
</ul>
</div>
</div>
//Knockout Js
function UserImageViewModel()
{
self=this;
var lastModelValue = (self.FeedPostdata()[self.FeedPostdata().length - 1]);
var lastPostImageId = (lastModelValue.ImageId())
//On Load More click last Image ID
self.getLoadMoreImageData=function()
{
$('#loading').show();
var UserModel = { userID:userID,ImageId:lastPostImageId}
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: "json",
url: serverUrl + 'api/xxx/xxx',
data: UserModel,
success: function (data) {
self.ImageList($.map(data, function (item) {
return new ImageModel(item);
}));},
complete: function () {
$('#loading').hide();
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);} });}}
// On Page Load without last Image ID
self.getALlUSerImage=function()
{
$('#loading').show();
var UserModel = { userID: userID}
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: "json",
url: serverUrl + 'api/xxx/xxx',
data: UserModel,
success: function (data) {
self.ImageList($.map(data, function (item) {
return new ImageModel(item);
}));},
complete: function () {
$('#loading').hide();
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);} });
}}
}
//Model//
function ImageModel(item)
{
self.userId=ko.observable(item.userId);
self.userName=ko.observable(item.UserName);
self.UserImageSrc = ko.computed(function () {
return "data:" + self.UserImageSrcType() + ";base64," + self.UserImageSrcBase64();});
self.ImageID=ko.observable(item.ImageId)
self.PostImageSrc = ko.computed(function () {
return "data:" + self.PostImageType() + ";base64," + self.PostImageBase64();});
}
$(document).ready(function () {
ViewModel = new UserImageViewModel();
ko.applyBindings(ViewModel);
}
How about something like this?
int Page = 1;
int RecordsPerPage = 10;
var q = yourQuery.Skip((Page - 1) * RecordsPerPage).Take(RecordsPerPage);

Passing response from ajax call to view in C#

I am using ajax to call an action in the controller. The code is like this
$('#kitchen').change(function () {
var selectedKitchen = $('#kitchen').val();
if (selectedKitchen != '') {
console.log("selected item:" + $('#kitchen').val());
$.ajax({
type: "GET",
url: "/Home/GiveInsitutionsWithoutResponsibility",
data: "id=" + selectedKitchen,
dataType:'json',
success: function (result) {
result = JSON.parse(result);
console.log(result.length);
},
error: function (error) {
console.log("There was an error posting the data to the server: ");
console.log(error.responseText);
}
});
}
});
Now what I want is to use the result coming from the server to populate a drop down on the client side. How should I do it? Is there a way for it or my approach here is wrong?
My result object is like this
{
Id: "04409314-ea61-4367-8eee-2b5faf87e592"
Name: "Test Institution Two"
NextPatientId: 1
OwnerId: "1"
PartitionKey: "1"
RowKey: "04409314-ea61-4367-8eee-2b5faf87e592"
Timestamp: "/Date(1417180677580)/"
}
The controller function is like this
public ActionResult GiveInsitutionsWithoutResponsibility()
{
var kitchenId = Request["id"].ToString();
Kitchen k = Kitchen.Get(kitchenId);
IEnumerable <Institution> ins = k.GetInstitutions();
IEnumerable<Institution> allIns = Institution.GetAll();
List<Institution> result = new List<Institution>();
bool contain = true;
int index = 0;
if (ins.Count() > 0)
{
for (int i = 0; i < allIns.Count(); i++, contain = true)
{
for (int j = 0; j < ins.Count(); j++)
{
if (allIns.ElementAt(i).Id == ins.ElementAt(j).Id)
{
contain = true;
break;
}
else
{
index = j;
contain = false;
}
}
if (!contain)
{
result.Add(allIns.ElementAt(index));
}
}
}
else
{
for (int i = 0; i < allIns.Count(); i++)
{
result.Add(allIns.ElementAt(index));
}
}
string response = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(result);
return Json(response, JsonRequestBehavior.AllowGet);
}
First your action method can be simplified to
public ActionResult GiveInsitutionsWithoutResponsibility(int ID)
{
Kitchen k = Kitchen.Get(ID);
var data = Institution.GetAll().Except(k.GetInstitutions(), new InstitutionComparer()).Select(i => new
{
ID = i.ID,
Name = r.Name
});
return Json(data, JsonRequestBehavior.AllowGet);
}
Note the Kitchen.ID is passed in the method parameter. The Linq query is used to select all Institution's then exclude any Institution's that already exist in the Kitchen, then creates a collections of anonymous object so unnecessary data is not sent to the client. The Json() method returns the data in the correct JSON format (calling JavaScriptSerializer().Serialize() is not required).
In order for .Except() to work with complex objects, you need a comparer
public class InstitutionComparer : IEqualityComparer<Institution>
{
public bool Equals(Institution x, Institution y)
{
if (Object.ReferenceEquals(x, y))
{
return true;
}
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
{
return false;
}
return x.ID == y.ID;
}
public int GetHashCode(Institution institution)
{
if (Object.ReferenceEquals(institution, null))
{
return 0;
}
return institution.ID.GetHashCode();
}
}
Next change the ajax method to
$('#kitchen').change(function () {
var selectedKitchen = $('#kitchen').val();
if (!selectedKitchen) {
return;
}
$.ajax({
type: "GET",
url: '#Url.Action("GiveInsitutionsWithoutResponsibility", "Home")', // don't hard code urls
data: { id: selectedKitchen }, // pass selectedKitchen to the id parameter
dataType:'json',
success: function (result) {
var select = $('YourDropDownSelector').empty().append($('<option></option>').val('').text('--Please select--'));
$.each(result, function(index, item) {
select.append($('<option></option>').val(item.ID).text(item.Name));
});
},
error: function (error) {
}
});
});
or you could use the short cut
$.getJSON('#Url.Action("GiveInsitutionsWithoutResponsibility", "Home")', { id: selectedKitchen }, function(result) {
$.each(result, .... // as above
});
Depending on the object from your controller, you could loop through your results data and .append this to your drop down list.
success: function (result) {
$.each(result, function(index, manager) {
$('select#yourId').append(
'<option value="' + result.Id + '">'
+ result.Name +
'</option>');
});
}
Your approach is fine, you will have to format the result to be added to combo box. For example, support on a page I have country and states combo box. Based on selected country, I need to populate state, so I will write following code:
$("#billingContactCountry").change(function (e) {
e.preventDefault();
var countryId = $("#billingContactCountry").val();
getStatesByCountry(countryId, "", "#billingContactState", "#billingContactZip");
});
function getStatesByCountry(countryId, stateId, stateCombobox, zipTextBox) {
$.ajax({
url: "#Url.Action("GetStatesByCountry", "Admin")",
data: { countryId: countryId },
dataType: "json",
type: "GET",
error: function (xhr, status) {
//debugger;
var items = "<option value=\"\">-Select State-</option>";
$(stateCombobox).html(items);
var zipMessage = validateZip(countryId, $(zipTextBox).val());
if (zipMessage != "The ZIP Code field is required.") {
$(zipTextBox).parent().find("span.field-validation-error").text(zipMessage);
}
$("div.overlay").hide();
},
success: function (data) {
//debugger;
var items = "<option value=\"\">-Select State-</option>";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Id + "\">" + item.Name + "</option>";
});
$(stateCombobox).html(items);
if (stateId != "") {
$('#billingContactState').val(stateId);
}
var zipMessage = validateZip(countryId, $(zipTextBox).val());
if (zipMessage != "The ZIP Code field is required.") {
$(zipTextBox).parent().find("span.field-validation-error").text(zipMessage);
}
$("div.overlay").hide();
}
});
}
So basically interesting code is,
var items = "<option value=\"\">-Select State-</option>";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Id + "\">" + item.Name + "</option>";
});
$(stateCombobox).html(items);
We are operating on each element returned from server to create option item for combo box.
As an aside, you should use #Url.Action as shown in example above.

JavaScript stop working after AJAX call

My javascript is getting locked after ajax call.
When the user press enter then i call my c# method to search the city that the user typed, and then show the temperature, but when the search ends, the javascript stops working. And i found out that the error is on these lines:
var div = document.getElementById('rb-grid');
div.innerHTML = resp.responseText + div.innerHTML;
code:
$(document).ready(function () {
$('#search-bar').keyup(function (event) {
if (event.keyCode == 13) {
myFunction();
}
});
function myFunction() {
var city = $('#search-bar').val();
$.ajax({
url: '#Url.Action("getWeatherSearch", "Index")',
data: { city: city },
async: false,
complete: function (resp) {
var div = document.getElementById('rb-grid');
div.innerHTML = resp.responseText + div.innerHTML;
Boxgrid.init();
}
});
} });
HTML:
<div align="center" class="div-search-bar">
#Html.TextBox("search-bar", "", new { #class = "search-bar", placeholder = "search" })
</div>
Try the following and see if it works for you:
$(function () {
var $searchbar = $('#search-bar'),
$grid = $('#rb-grid');
if ($grid.length) {
$searchbar.on('keyup', function (event) {
if (event.keyCode == 13) {
myFunction();
}
});
function myFunction() {
var city = $searchbar.val();
$.ajax({
url: $.grid.data('weather-url'),
data: { city: city }
})
.done(function (resp) {
$grid.html(resp.responseText + $grid.html());
Boxgrid.init();
}
});
}
}
});
Add the following as a data attribute somewhere in your html, probably on your grid:
<div id='rb-grid' data-weather-url='#Url.Action("getWeatherSearch", "Index")'></div>

not able to display employee details in html table in view using json

I have got problem with displaying employee details in view when the user clicks the button on view..
when the user clicks the button the employee details(both id and name) will be called through the JSON and displaying data in html table, for that purpose I have written like this in my view
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = '/EmpDetails/GetEmployees/';
$.getJSON(url, function (data) {
$.each(data, function (key, Val) {
var user = '<tr><td>' + Val.EmployeeId + '<td><tr>' + '<tr><td>' + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
});
});
</script>
#{
ViewBag.Title = "GetEmployeesByName";
}
<h2>GetEmployeesByName</h2>
#using (Html.BeginForm())
{
<table id ="parenttable"></table>
<input id="submitbtnn" type="Submit" value="Submit1" />
}
and this is my controller, here i am returning json data to view
namespace MvcSampleApplication.Controllers
{
public class EmpDetailsController : Controller
{
[HttpGet]
public ActionResult GetEmployees()
{
List<EmployeeClass> employees = new List<EmployeeClass>();
EmployeeClass employee1 = new EmployeeClass { EmployeeId=1, EmployeeName = "Rams"};
EmployeeClass employee2 = new EmployeeClass { EmployeeId = 2, EmployeeName = "joseph" };
EmployeeClass employee3 = new EmployeeClass { EmployeeId = 3, EmployeeName = "matt" };
employees.Add(employee1);
employees.Add(employee2);
employees.Add(employee3);
return Json(employees, JsonRequestBehavior.AllowGet);
}
}
}
but I am getting http 404 resource not found error, when i am trying to access this url
http://localhost/EmpDetails
would any one pls suggest any ideas and any suggestions on this,that would be very greatful to me..
Many thanks...
Modified View
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = #Url.Action("GetEmployees","EmpDetails")
//alert("hi");
$.getJSON(url, function (data) {
//alert("hi");
$.each(data, function (Val) {
var user = '<tr><td>' + Val.EmployeeId + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
return false;
});
});
</script>
#{
ViewBag.Title = "GetEmployeesByName";
}
<h2>GetEmployeesByName</h2>
#using (Html.BeginForm())
{
<div class="temptable">
<table id ="parenttable"></table>
</div>
<input id="submitbtnn" type="Submit" value="Submit1" />
}
I am not able to hit second Alert Function inside JavaScript function.
You forgot to cancel the default action of the button by returning false from the click handler:
$('#submitbtnn').click(function () {
var table = $('#parenttable');
var url = '/EmpDetails/GetEmployees/';
$.getJSON(url, function (data) {
$.each(data, function (key, Val) {
var user = '<tr><td>' + Val.EmployeeId + '<td><tr>' + '<tr><td>' + Val.EmployeeName + '<tr><td>'
table.append(user);
});
});
return false; // <!-- This is very important
});
By not canceling the default action, when you click on the submit button, the browser submits the form and redirects away from the page to the action of the form leaving no time for the AJAX request to ever execute.
Try using this as your url #Url.Action("GetEmployees","EmpDetails")
Try this
$(function () {
$('#submitbtnn').click(function () {
var table = $('#parenttable');
$.ajax({
url: 'GetEmployees',
type: 'POST',
data: JSON.stringify({ table: table }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var rowcount = data.employees.length;
for (var i = 0; i < rowcount; i++) {
var user = '<tr><td>' + employees[i].EmployeeId + employees[i].EmployeeName + '<tr><td>'
table.append(user);
}
});
},
error: function () {
alert('fail');
}
});
return false;
});

Knockout - Fetching paginated data, initial load

I'm building a simple paginated table view with KnockoutJS and Twitter Bootstrap. Right now I have everything working except that I can't get the initial dataset to load when the page loads. Looking at my view model, you can see that the proper data loads when "navigating" trough the customer repository via a RESTful API.
How can I get the initial data to load?
<script>
var ListViewModel = function() {
var self = this;
window.viewModel = self;
//Properties
self.list = ko.observableArray();
self.pageSize = ko.observable(20);
self.pageIndex = ko.observable(0);
self.itemCount = ko.observable();
self.maxPageIndex = ko.dependentObservable(function () {
return Math.ceil(self.itemCount() / self.pageSize()) - 1;
});
self.allPages = ko.dependentObservable(function () {
var pages = [];
for (i = 0; i <= self.maxPageIndex() ; i++) {
pages.push({
pageNumber: (i + 1)
});
}
return pages;
});
//navigation Functions
self.previousPage = function () {
if (self.pageIndex() > 0) {
self.pageIndex(self.pageIndex() - 1);
}
self.getItems();
};
self.nextPage = function () {
if (self.pageIndex() < self.maxPageIndex()) {
self.pageIndex(self.pageIndex() + 1);
}
self.getItems();
};
self.moveToPage = function (index) {
self.pageIndex(index);
self.getItems();
};
//API interactions
self.getItems = function () {
$.ajax({
url: '/api/customer/?pageNumber='+self.pageIndex()+"&pageSize="+self.pageSize(),
async: false,
dataType: 'json',
success: function (result) {
self.list(result);
}
});
};
self.getTotalItemCount = function() {
//TODO: Add call to fetch total number of customers in the database and set it to self.itemCount property.
};
};
$(document).ready(function() {
ko.applyBindings(new ListViewModel());
});
</script>
Change you start code
$(document).ready(function() {
var vm = new ListViewModel()
vm.getItems()
ko.applyBindings(vm)
});

Categories

Resources