Jquery Autocomplete + ASP.NET MVC 3 not displaying the results - c#

My View Code:
Script and Css:
<link href="#Url.Content("~/Content/jquery-ui-1.8.18.custom.css")" rel="stylesheet"type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.18.custom.min.js")" type="text/javascript"></script>
Input text:
#Html.TextBoxFor(model => model.Filter.HouseName, new { style = "width: 205px", onKeyUp = "updateHouseNames()" })
Javascript:
function updateHouseNames() {
var houseArray = new Array();
$.post('#Url.Action("LoadHouses")', { houseName: $("#Filter_HouseName").val() }, function(houses) {
houseArray = houses;
});
$("#Filter_HouseName").autocomplete({
source: houseArray
});
}
Controller method:
[HttpPost]
public JsonResult LoadHouses(string houseName)
{
var houses = this.HouseService.SelectByName(houseName).Select(e => new String(e.Name.ToCharArray())).ToArray();
return Json(houses);
}
I debug the javascript and the houses are selected.. but the results are not displayed in autocomplete. Why?

I don't really think you should be doing it this way. If you need to customize the logic then use a callback on the autocomplete method:
$(function () {
$('#Filter_HouseName').autocomplete({
minLength: 1,
source: function (request, response) {
var term = request.term;
var houseArray = new Array();
$.post('#Url.Action("LoadHouses")', { houseName: term }, function(houses) {
houseArray = houses;
response(houseArray);
});
}
});
});

Related

asp.net Razor Pages - Update select list based on the selection of another select list

I want to update a select list when the user selects a value in another select list. I've managed to get the first select list to call a get (or post) method on the model with a parameter, and can update the underlying data. But the second select list never shows the new values.
I'm not very experienced with asp.net, so what am I doing wrong?
Code below
.cshtml
<div>
<form method="post">
<select id="departureStation" asp-items="Model.DepartureStations" onchange="getDestinationStations()"></select>
<select id="destinationStation" asp-items="Model.DestinationStations"></select>
</form>
</div>
#section Scripts {
<script type="text/javascript">
function getDestinationStations() {
var selectedDepartureStationID = $("#departureStation").find(":selected").val();
console.log("selectedDepartureStationID = " + selectedDepartureStationID);
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
console.log("success - " + result);
},
error: function() {
console.log("failure");
}
})
}
</script>
}
.cs
public List<SelectListItem> DestinationStations
{
get
{
if (this._selectedDepartureStationID == -1)
return new List<SelectListItem>();
List<Models.Station> stations = new List<Models.Station>();
List<Models.RouteSegment> routeSegments = this._context.RouteSegments.Where(x => x.StationID == this._selectedDepartureStationID).ToList();
foreach (Models.RouteSegment routeSegment in routeSegments.DistinctBy(x => x.RouteID))
{
List<Models.RouteSegment> routeSegments2 = this._context.RouteSegments.Where(x => x.RouteID == routeSegment.RouteID).Include(x => x.Station).ToList();
stations.AddRange(routeSegments2.Select(x => x.Station));
}
return new List<SelectListItem>(stations.Distinct().ToList().Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList());
}
}
public IndexModel(MyViewContext context)
{
this._context = context;
}
public void OnGet()
{
this.DepartureStations = this._context.Stations.Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList();
}
public IActionResult OnGetDeparture(int selectedDepartureStationID)
{
this._selectedDepartureStationID = selectedDepartureStationID;
return Page();
}
Whenever your #departureStation select changes, your code will call getDestinationStations javascript code. Inside that function you are sending a request to your backend server to receive possible destination stations if I understood correctly. What you need to do here is when ajax request successes, add options dynamically based on your returned array or data.
I am assuming your "/Index?handler=Departure" returns a JSON like:
[
{
id: 1,
name: "station1"
},
{
id: 2,
name: "station2"
}
]
Check if code below works.
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
let destinationStationSelect = $('#destinationStationSelect');
let optionTemplate = $('<option></option>');
$.each(result, (index, element) => {
let option = optionTemplate.clone();
option.append(element.name);
option.attr('value', element.id);
destinationStationSelect.append(option);
});
},
error: function() {
console.log("failure");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to I call 2 variables in Vuejs?

I am using Vuejs.
And I want to call 2 variables.
How should I do?
These are my real codes.
(I want to add a codes that will hide the (x) button in a modal with a class [.close])
I edited my previous post. Sorry 'bout that.
window.app = new Vue({
el: '#vuelayoutdiv',
data: {
text: null
},
methods: {
submitToSignIn: function () {
window.location.href = "/{Contoller}/{Index}"
},
checkEmail: function (e) {
if (this.text) {
return true;
};
if (!this.text) {
this.$bvModal.show('emailmodal');
}
}
}
});
<b-modal id="emailmodal" hide-footer>
#*<template v-slot:modal-title>
Using
<code>$bvModal</code> Methods
</template>*#
<div class="d-block text-center">
<h3 style="text-align:left">Email required.</h3>
</div>
<b-button class="mt-3" block v-on:click="$bvModal.hide('emailmodal')">Close Me</b-button>
</b-modal>
<b-nav-item class="navbarsigntext signin" v-on:click="submitToSignIn">SIGN IN</b-nav-item>
It's easy to access other Vue instances variables. Although this isn't really common practice, and I'm not really sure what you are trying to do.
Here is an example, where there is thre instances in total, where the third, gets the message variable from object one and two.
var vueObj1 = new Vue({
data () {
return {
message: "vueobj1"
}
},
})
var vueObj2 = new Vue({
data () {
return {
message: "vueobj2"
}
},
})
var vueObj3 = new Vue({
el: '#app',
computed: {
messageFromOtherInstances () {
return vueObj1.message + ' ' + vueObj2.message
}
}
})
I've a small codepen for you, to play with: https://codepen.io/dasmikko/pen/XWWybdr
Use data as a function and return your variables.
Read the syntax in Vue js : - https://v2.vuejs.org/v2/guide/components.html
var variable1 = new Vue({
el: '#app1',
data () {
return {
text1:"sample"
}
},
})
var variable2 = new Vue({
el: '#app2',
data () {
return {
text2:"sample"
}
}
})
<script src="https://unpkg.com/vue#2.5.9/dist/vue.js"></script>
<div id="app1">
{{ text1 }}
</div>
<div id="app2">
{{ text2 }}
</div>

C# Mvc Web Api Cascading List

This is my controller.
public class DokuzasController : Controller
{
public ActionResult AddOrEdit()
{
DersViewModel model = new DersViewModel();
schoolEntities sc = new schoolEntities();
List<ders> dersList = sc.ders.OrderBy(f => f.Ders1).ToList();
model.DersList = (from s in dersList
select new SelectListItem
{
Text = s.Ders1,
Value = s.DersID.ToString()
}).ToList();
model.DersList.Insert(0, new SelectListItem { Value = "", Text = "Select"});
return View(model);
}
[HttpPost]
public ActionResult AddOrEdit(DersViewModel model)
{
if (model.LectureId == 0)
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PostAsJsonAsync("dokuzas", model).Result;
TempData["SuccessMessage"] = "Saved.";
}
else
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PutAsJsonAsync("dokuzas/" + model.LectureId, model).Result;
TempData["SuccessMessage"] = "Successful.";
}
return RedirectToAction("Index");
}
[HttpPost]
public JsonResult SaatList(int id)
{
schoolEntities sc = new schoolEntities();
List<saat> saatList = sc.saat.Where(f => f.DersID == id).OrderBy(f => f.Saat1).ToList();
List<SelectListItem> itemList = (from i in saatList
select
new SelectListItem
{
Value = i.SaatID.ToString(),
Text = i.Saat1
}).ToList();
return Json(itemList, JsonRequestBehavior.AllowGet);
}
}
And this is my AddOrEdit file.
#model Mvc.Models.DersViewModel
#{
ViewBag.Title = "AddOrEdit";
}
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownListFor(m => m.DersID, Model.DersList)
<br /><br />
#Html.DropDownListFor(m => m.SaatID, Model.SaatList)
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#DersID").change(function () {
var id = $(this).val();
var saatList = $("#SaatID");
saatList.empty();
$.ajax({
url: '/Dokuzas/SaatList',
type: 'POST',
dataType: 'json',
data: { 'id': id },
success: function (data) {
$.each(data, function (index, option) {
saatList.append('<option value=' + option.Value + '>'
+ option.Text + '</option>')
});
}
});
});
});
</script>
}
I have a table and this table contains Dersadi and Dagilimi properties. I wanted to create a cascading list and add to table from this list from DersList to Dersadi and from SaatList to Dagilimi. But i choose items and select submit button i can submit it but it added null to the table. It did not add what i choose from the list. How can i fix this?
in the view, you can use the DropDownList helper method to render the SELECT element with the data we set to the Model.DersList. We will also add our second dropdown as well.
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownList("DersID", Model.DersList as SelectList)
<select name="id" id="SaatID" data-url="#Url.Action("SaatList","Home")">
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
<script type="text/javascript">
$(function(){
$("#DersID").change(function (e) {
var $SaatID = $("#SaatID");
var url = $SaatID.data("url")+'?id='+$(this).val();
$.getJSON(url, function (items) {
$.each(items, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
});
});
});
</script>

How get value from cascading drop down list made with ajax

I am very new to MVC, and am try to set up a series of cascading drop down lists using this example.
But I am stuck a little bit, because I don't know how to get the value from the second drop down and send it to controller when I press the appropriate button.
Here is my view:
<script type="text/javascript">
$('#list').change(function() {
var selectedClient = $(this).val();
if (selectedClient != null && selectedClient != '') {
$.getJSON('#Url.Action("SelectC")', { clientID: selectedClient }, function (client) {
var campaingSelect = $('#clist');
campaingSelect.empty();
$.each(client, function(index, clients) {
campaingSelect.append($('<option/>', {
value: clients.value,
text: clients.text
}));
});
});
}
});
</script>
#using (Html.BeginForm("CreateNewCampaign", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.LabelFor(m => m.alreadyCreatedCampaignName, "Name:")
#Html.DropDownList("clist","-- Select Client -2-")
<input type="Submit" name="button" value="Select" class="btn btn-primary" />
}
Controller:
public ActionResult SelectC(int clientId, CampaignModel model, FormCollection form)
{
Session["ClientID"] = clientId;
ViewBag.ClientName = "You're using: " + Session["ClientName"];
var CampaignInf = CampaignManagementService.GetCampaigns((string) Session["ticket"], clientId);
List<AlreadyCreatedCampaignList> itemas = new List<AlreadyCreatedCampaignList>();
foreach (var element in CampaignInf)
{
itemas.Add(new AlreadyCreatedCampaignList() {CampId = element.Key, CampName = element.Value});
}
var listOfCam = new SelectList(itemas, "campID", "campName", 1);
return Json(listOfCam.Select(x => new {value = x.Value, text = x.Text}), JsonRequestBehavior.AllowGet);
}
I want to get the value to other controller, and I am not sure of the right way to go about doing this.
You can get value of dropdownlist just by giving it ID and call $("#id").val();, then you can transfer it to the controller through ajax maybe.
Here is mine, try it
public ActionResult ActionName(string dropdown_value){
//your code
}
<script>
$(document).ready(function(){
$("submit").click(function(){
$.ajax({
url:"Controller/ActionName",
datatype: "POST",
data: { dropdown_value : $("#clist").val() },
success : function(){ //your code if success }
});
});
});
</script>

Get data from a controller, return as json and preview in cshtml

I have a controller that I get result exampleController.cs:
public expChart{
...
public ActionResult ByContainer(int id)
{
var elementIds = _systemSettings.Z3FromZBIds; // CritialWorkPermitIds;
var kpiElements = CacheService.AllVisibleElements
.Where(x => elementIds.Contains(x.Id)).ToList();
var container = _kpiContainerService.Find(id);
var result = _kpiTrendService.MonthByContainer(kpiElements, container);
return AsJson(result);
}
}
I call it in example.cshtml:
<div class="panel" style="display: none;" id="bottom-area-trend-charts" ng-ontroller="exampleController">
<div >
TEST
{{element.Name}}
</div>
</div>
I think it is something wrong with my calling. How can I call the result in my controller?
Thanks in advance
Use something like this:
<script type="text/javascript">
$(function () {
$.ajax({
url: "/YourController/ByContainer",
type: "GET",
dataType: 'html',
data: { id: 10 }, // the value id for call your controller
success: function (data) {
// make sure your result variable is enumerable.
$(data).each(function (index, element) {
$("#bottom-area-trend-charts div").append("<p>" + element.Name + "</p>");
});
},
error: function (xqr, errorMessage) {
alert(errorMessage);
}
});
});
</script>
And change your action to this:
public JsonResult ByContainer(int id)
{
var elementIds = _systemSettings.Z3FromZBIds; // CritialWorkPermitIds;
var kpiElements = CacheService.AllVisibleElements
.Where(x => elementIds.Contains(x.Id)).ToList();
var container = _kpiContainerService.Find(id);
var result = _kpiTrendService.MonthByContainer(kpiElements, container);
return Json(result, JsonRequestBehavior.AllowGet);
}

Categories