ASP.NET MVC Cascading DropDownLists Javascript Issues - javascript

After reviewing many tutorials and various approaches to Cascading DropDownLists, I decided to create a ViewModel for my View and then populate my DropDownLists based on this post:
MVC3 AJAX Cascading DropDownLists
The goal here is the most basic and covered in many tutorials, but I still can't get it quite right... to populate a City dropdown based on the value of a State dropdown.
EDIT:
Since posting this request for help, I discovered Firebug (yes, that's how new I am to doing any sort of programming), and I was able to determine that I am successfully calling my controller, and pulling the necessary data. I believe the problem is the second half of my JavaScript that returns the data to my View.
Here is my View:
<label>STATE HERE:</label>
#Html.DropDownListFor(x => x.States, Model.States, new { #class = "chzn-select", id = "stateID" })
<br /><br />
<label>CITY HERE:</label>
#Html.DropDownListFor(x => x.Cities, Enumerable.Empty<SelectListItem>(), new { id = "cityID" })
Here is the JavaScript within my View, and somehow I'm not handling my results correctly once I get them:
$(function () {
$("#stateID").change(function () {
var stateId = $(this).val();
// and send it as AJAX request to the newly created action
$.ajax({
url: '#Url.Action("GetCities")',
type: 'GET',
data: { Id: stateId },
cache: 'false',
success: function (result) {
var citySelect = $('#cityID');
$(citySelect).empty();
// when the AJAX succeeds refresh the ddl container with
$.each(result, function (result) {
$(citySelect)
.append($('<option/>', { value: this.simpleCityID })
.text(this.cityFull));
});
},
error: function (result) {
alert('An Error has occurred');
}
});
});
});
Here is my controller called by the JavaScript:
public JsonResult GetCities(int Id)
{
return Json(GetCitySelectList(Id), JsonRequestBehavior.AllowGet);
}
private SelectList GetCitySelectList(int Id)
{
var cities = simpleDB.simpleCity.Where(x => x.simpleStateId == Id).ToList();
SelectList result = new SelectList(cities, "simpleCityId", "cityFull");
return result;
}
Here are my results from Firbug, which tell me I'm building and getting the data without issue, just not populating my DropDownList correctly:
[{"Selected":false,"Text":"Carmel","Value":"IN001"},{"Selected":false,"Text":"Fishers","Value":"IN002"}]
If anyone has any suggestions as to why the JavaScript fails to populate the dropdrown, please comment, thanks!

I have done this several times with something like this:
Create a partial to popolate dropdown list. Name it DropDownList and put in Shared folder of Views
#model SelectList
#Html.DropDownList("wahtever", Model)
Your create view should be something like this (skipped irrelevant parts)
<script type="text/javascript">
$(function() {
$("#StateId").change(function() {
loadLevelTwo(this);
});
loadLevelTwo($("#StateId"));
});
function loadLevelTwo(selectList) {
var selectedId = $(selectList).val();
$.ajax({
url: "#Url.Action("GetCities")",
type: "GET",
data: {stateId: selectedId},
success: function (data) {
$("#CityId").html($(data).html());
},
error: function (result) {
alert("error occured");
}
});
}
</script>
#Html.DropDownList("StateId")
<select id="CityId" name="CityId"></select>
Carefully note the Empty Select item for CityId and the call of loadLevelTwo at document.ready
And your controller should be like:
public ActionResult Create()
{
ViewBag.StateId = new SelectList(GetAllCities(), "Id", "Name");
return View();
}
public ActionResult GetCities(int stateId) {
SelectList model = new SelectList(GetCitiesOfState(stateId), "Id", "Name");
return PartialView("DropDownList", model);
}

Thank you for your assistance,
It turns out that in my JavaScript below, I was attempting to directly reference the simpleCityID and cityFull fields associated with my data model:
$.each(result, function (result) {
$(citySelect)
.append($('<option/>', { value: this.simpleCityID })
.text(this.cityFull));
Instead, I needed to keep it generic and inline with JavaScript standards of referencing Value and Text:
$.each(modelData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text

Related

How to display the information from the input box

I am trying to learn how to work with angular and javascript more. Please let me know what I am doing wrong here.
When I input something into the text box, it should display
"hello {name} , would you like to play a game?
It displays the string without the input.
Also, when I run it, it says
object Object
.
(function (app) {
var JakesController = function ($scope, $http) {
$scope.JakesSampleModel = {name: ' '};
$scope.theSampleReturn = null;
var sendResponseData = function (response) {
if (response.data.error) {
console.log(data);
}
else {
$scope.theSampleReturn = response.data;
}
};
var sendResponseError = function (data) {
console.log(data);
}
$scope.senddata = function (params) {
return $http({
method: 'post',
url: '/home/servercall',
data: params
})
.then(sendResponseData)
.catch(sendResponseError);
};
};
app.controller("JakesController",['$scope', '$http', JakesController]);
}(angular.module("JakesFirstApp")));
Here is the HTML:
<div id="OutterDiv" ng-controller="JakesController" ng-app="JakesFirstApp">
<div id="JakesButton" class="button" ng-click="senddata()">Submit</div>
<input type="text" id="JakesTextBox" ng-model="theSampleReturn" />
{{theSampleReturn.result}}
Json result:
public JsonResult servercall(string name)
{
return Json(new { result = $"Hello {name}, Would you like to play a game?" }, JsonRequestBehavior.AllowGet);
}
In your html try to use {{theSampleReturn}} instead of {{theSampleReturn.result}} because you don't seem to have theSampleReturn.result set anywhere
If I understand you question correctly, then it looks like the solution is to update your template like so:
<input type="text" id="JakesTextBox" ng-model="JakesSampleModel.name" />
And then update your controller to correctly send the name to the server when senddata() is called:
$scope.senddata = function () {
// Construct params for post by getting data from your scope/model that's
// wired up to your input field
var params = { name : $scope.JakesSampleModel.name };
return $http({
method: 'post',
url: '/home/servercall',
data: params
})
.then(sendResponseData)
.catch(sendResponseError);
};

autocomplete and multiple function using ajax in laravel

I am new to laravel framework. I want to complete a important task in my app.
In that app they have modules like invoices,quotes,payment,customers. for particular customers they have multiple invoices with status of sent and partially paid.
Here is the receipt page, on type of customer name it will get autosuggestion from customer table. Onclick of cutomer name it will get invoice details from (invoice table) based on customer id,and need to show on table below that customer name textbox, onclick of table invoice it will open modal which means if the particular customer has unpaid invoice they need to record payment else proceed with normal receipt creation.
I try the code like this, But I am not getting proper output please anyone help me to get out of this issue.
<input type="text" name="customername" required="required" id="cust" placeholder="Customer Name" class="form-control col-md-7 col-xs-12 typeahead"/>
$( function() {
$( "#cust" ).autocomplete({
//source: "http://www.duminex.com/client/search",
source: "{{route('search.client')}}",
select: function( event, ui ) {
get_invoices(ui.item.id);
$('#id').val(ui.item.id);
$('#clientAddress').val(ui.item.address);
}
});
} );
function get_invoices(client_id)
{
$.ajax({
method: 'GET',
url: "{{route('client.details')}}"
}).done(function(data){
alert(data);
});
}
routes
Route::get('/client/search',[
'uses'=>'ClientsController#search',
'as'=>'search.client'
]);
Route::get('/client/search2', 'ClientsController#search2')->name('client.details');
Controller
public function search(Request $request)
{
$s= Input::get('term');
$clients = Client::select("id" ,"user_id", "companyname", "companyaddress" , "billingAddress")->where('companyname','like','%'.$s.'%')->where('user_id',Auth::user()->id)->get();
if(count($clients) == 0){
$searchResult[] = "No Item found";
}
else{
foreach ($clients as $key => $value) {
$searchResult[] = ['id' => $value->id, 'value' => $value->companyname , 'email' => $value->companyaddress , 'address' => $value->billingAddress];
}
}
return $searchResult;
}
public function search2(Request $request)
{
$clients = Invoice::select("invoiceNo")->where('status',['sent,Partially paid'])->where('client_id',$request->client_id)->get();
if(count($clients) == 0){
$searchResult[] = "No Item found";
}
else{
foreach ($clients as $key => $value) {
$searchResult[] = ['invoiceNo' => $value->invoiceNo];
}
}
return $searchResult;
}
Thanks in advance. Please anyone to help me get out of this issue.
You are not passing any data to the ajax so thats why you are not getting any result.
Try below code :
function get_invoices(client_id) {
$.ajax({
method: 'GET',
data : {
client_id: client_id
},
url: "{{route('client.details')}}"
}).done(function(data){
alert(data);
});
}

get a view page using jquery in mvc4

Hi I am working with mvc4
I have a razor view page for the action
public ActionResult DeliveryAddress(string userid,int productid)
{
....
return View(m);
}
that contain
<div >DELIVER HERE</div>
when clicking on this i am collecting somedata ifrom this page using jquery,
$(document).ready(function () {
$("#place-order").click(function () {
var userid = $('#selected-userId').html();
var productid = $('#selected-productId').html();
$.get("Products/PlaceOrder/"+ userid, function (data) { });
});
});
and i want to pen another view of action
[HttpGet]
public ActionResult PlaceOrder(int uid)
{
return View();
}
and paste the variable content,
but $.get("Products/PlaceOrder", function (data) { }); is not hitting this action..
please help me.
This is how you need to pass a data to a url in Jquery get method, note the same parameter name is used in the function
$.get('#Url.Action("PlaceOrder","Products")', { uid: userid }, function (data)
{
});
Make sure your URL is correct. Most probably use #Url.Action(). and also pass the parameter using new as shown below.
$.get('#Url.Action("PlaceOrder","Products",new { userid = #userid , productid = #productid })', function (data) {
});
While collecting the data make sure your parameter names are same for both while sending and while receiving.
[HttpGet]
public ActionResult PlaceOrder(int userid, int productid )
{
return View();
}
Just add HTTPGET attribute in your action method as below.
[HttpGet]
public ActionResult PlaceOrder()
{
return View();
}
java script
$("#place-order").click(function () {
var userid = $('#selected-userId').html(); // $('#selected-userId').val();
$.get('#Url.Action("PlaceOrder","Products", new { uid = userid })', function (data) { });
var productid = $('#selected-productId').html();
});
When I want my view code to be fetched like that, or even through the Html.Action() call, I use the PartialView and normally set my Controller Action as:
public ActionResult PlaceOrder(int uid)
{
return PartialView(new TestViewModel() { ID = uid });
}
as an example:
TestViewModel
public class TestViewModel
{
public int ID { get; set; }
}
PlaceOrder.cshtml
#model TestViewModel
<h2>Partial View</h2>
<p>
Partial View paragraph with the id <b>#Model.ID</b>
</p>
Index.html
<hr />
#Html.Action("PartialView", "Home", new { id = 44 })
<hr />
<div class="ap"></div>
<script>
var url = '#Url.Action("PartialView", "Home")';
$.get(url, { id: 54 }, function (data) {
$(".ap").append(data);
});
</script>
result:

Item selection MVC view with KnockoutJS

I am trying to implement a generic ASP.net MVC view. The UI should display a list of available and selected items loading data (basically list of string) from server. User can make changes into the list i.e. can select new items from available item list and also can remove items from selected list.
I wanted to do it using KnockoutJS as to take advantage of binding.
I manage to complete it upto the point everything is working except showing selected item as checked when the view is initialized in available list. E.g. As Shown Here
I tried various options (using template (closest to what I want to achieve), Checked attr, possible options), the issue is if I manage to display item checked some other functionality breaks. Tried defining a template but could not get it to work in my case.
HTML:
<div class='moverBoxOuter'>
<div id='contactsList'>
<span data-bind="visible: availableItems().length > 0">Available countries: </span>
<ul data-bind="foreach: availableItems, visible: availableItems().length > 0">
<li>
<input type="checkbox" data-bind="checkedValue: $data, checked: $root.selectedItems" />
<span data-bind="text: title"></span>
</li>
</ul>
<span data-bind="visible: selectedItems().length > 0">Selected countries: </span>
<ul data-bind="foreach: selectedItems, visible: selectedItems().length > 0">
<li>
<span data-bind="text: title"></span>
Delete
</li>
</ul>
</div>
JS:
var initialData = [
{
availableItems: [
{ title: "US", isSelected: true },
{ title: "Canada", isSelected: false },
{ title: "India", isSelected: false }]
},
{
selectedItems: [
{ "title": "US" },
{ "title": "Canada" }
]
}
];
function Item(titleText, isSelected) {
this.title = ko.observable(titleText);
this.isSelected = ko.observable(isSelected);
}
var SelectableItemViewModel = function (items) {
// Data
var self = this;
self.availableItems = ko.observableArray(ko.utils.arrayMap(items[0].availableItems, function (item) {
return new Item(item.title, item.isSelected);
}));
self.selectedItems = ko.observableArray(ko.utils.arrayMap(items[1].selectedItems, function (item) {
return new Item(item.title, item.isSelected);
}));
// Operations
self.selectItem = function (item) {
self.selectedItems.push(item);
item.isSelected(!item.isSelected());
};
self.removeItem = function (removedItem) {
self.selectedItems.remove(removedItem);
$.each(self.availableItems, function (item) {
if (item.title === removedItem.title) {
item.isSelected = false;
}
});
};
}
var vm = new SelectableItemViewModel(initialData);
$(document).ready(function () {
ko.applyBindings(vm);
});
Could you please help, see jsfiddle below:
http://jsfiddle.net/sbirthare/KR4a6/6/
**Update: Follow up question below **
Its followup question:
I need to add a combobox on same UI e.g. for US state. The available items are counties, based on user selection in state combo I need to filter out counties. I am getting data from server using AJAX and its all successful BUT the displayed list is not refreshing. I was expecting having binding setup correctly, if we change the observable array in viewmodel, the UI should change. I tried forcing change to availableItems but it just display all items. Please see if you can spot the problem in below code where I am updating ViewModel observable array.
function multiselect_change() {
console.log("event: openmultiselect_change");
var selectedState = $("#stateDropdownSelect").val();
var propertyName = $("#PropertyName").val();
var searchId = #Model.SearchId;
var items;
var model = { propertyName: propertyName, searchId: searchId, stateName: selectedState };
$.ajax({
url: '#Url.Action("GetFilterValues", "Search")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'html',
data: JSON.stringify(model)
})
.success(function(result) {
debugger;
items = JSON.parse(result);
vm.availableItems(items.AvailableItems);
//vm.availableItems.valueHasMutated();
//var item = document.getElementById('availableItemId');
//ko.cleanNode(item);
//ko.applyBindings(vm, item);
vm.filter(selectedState);
})
.error(function(xhr, status) {
alert(status);
});
}
As user3426870 mentioned, you need to change the value you passed to the checked binding to boolean.
<input type="checkbox" data-bind="checkedValue: $data, checked: isSelected" />
Also, I don't think you need to have selectedItems in the initial data.
Instead in the viewModel, you can do something like:
self.selectedItems = ko.computed(function() {
return ko.utils.arrayFilter(self.availableItems(), function (item) {
return item.isSelected();
});
});
It's because you give an array to the binding checked while it's supposed to be a value comparable to true or false (like undefind or an empty string).
I would use a function checking if the $data is in your array and returning a boolean to your binding.
Something like that!

Angularjs populating dropdown with in ng-repeat from different scope

Hi I have following controller which gets data from database using factory which works fine.
My service is
App.factory("pOvRepository", ['$resource', function ($resource) {
return {
pw: $resource('/api/pOv/:id', { id: '#id' }, { update: { method: 'PUT' } }),
ps: $resource('/api/pStatus/:id', { id: '#id' }, { update: { method: 'PUT' } })
};
}]);
Controller is
App.controller('pOvCtrl', function ($scope, pOvRepository, $location) {
$scope.poviews = pOvRepository.pw.query();
$scope.pS = pOvRepository.ps.query();
The data I get for $scope.pS is
[{"p_status1":"Up Coming","p_id":1,"proj":[]},
{"p_status1":"In Progress","p_id":2,"proj":[]},
{"p_status1":"On Hold","p_id":3,"proj":[]}]
In my html code I am trying to populate the dropdown with data from $scope.pS
<div ng-controller="pOvCtrl">
<form ng-repeat="p in poviews">
<input type="text" ng-model="p.include_in"/>
<select ng-model="p.p_id" ng-options="a.p_status1 as a.p_id for a in pS"></select>
</form>
When I run it, the dropdown does not get populated with the options from $scope.pS
Please let me know how I can fix it.
Thanks
Hard to tell without seeing your service, you need to specify a callback for the data:
pOvRepository.ps.query({}, function(data) {
$scope.pS = data;
});

Categories