I am trying to use select2 with ASPX calling a webmethod. I am not able to get the ajax web method called within the select2 java script method above. any idea what i am doing incorrectly ?
this is my control on the page
<input type="hidden" id="attendee" style="width:300px;" /
this is my javascript code
$(document).ready(function () {
$('#attendee').select2(
{
placeholder: 'Enter name',
minimumInputLength: 1,
allowClear: true,
ajax:{
type: "POST",
url: "TestClientPage2.aspx/GetClientList",
dataType: 'json',
data: function (term, page) {
return {
pageSize: 20,
pageNum: page,
searchTerm: term
};
},
results: function (data, page) {
var more = (page * pageSize) < data.Total;
return { results: data.results, more: more };
}}});
});
This is my web method
public static string GetClientList(string searchTerm)
{
return #"{""employees"": [{ ""firstName"":""John"" , ""lastName"":""Doe"" }]}";
}
Related
I'm working on an autocomplete that calls a method on my home controller, the javascript calls the method and returns the array. However the values do not display on the text box drop down, nothing does.
If I use a straight array as the source and don't call the home controller then it works just fine.
I don't see what I'm missing here, so I narrowed down the home controller method just to return an array using no logic until I figure this problem out.
Home Controller Method:
public string[] GetPatientName()
{
var names = new List<string> { "Bent","Boon","Book", "Al", "Cat", "Doe", "Ed", "Fox", "George" };
return names.ToArray();
}
Javascript:
<script language="javascript" type="text/javascript">
$(function() {
$('#tags').autocomplete({
source: function(request, response) {
$.ajax({
url: "/Home/GetPatientName",
data: "{ 'pre':'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
response($.map(data.d,
function (item) {
alert(item);
return { value: item }
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
delay: 0
});
});
</script>
HTML
<form>
<input id="tags" type="text" />
</form>
2 things:
1. From the top of my mind, if it wirked with a regular array and didnt work with the result of jQuery map function you probably need to ad .get() in order to get a clean array. To be precise
$.map(data.d,function (item) {
alert(item);
return { value: item }
}).get();
2. If that doesnt work, you would really have to share more data like what is the "response" function and exactly what response you are getting from the server (you could get that from the web browser's dev tools)
I have a HTML dropdown list for countries. Now I want to populate the City dropdown accordingly using ajax
<select class="form-control" id="ddCountry" runat="server" tabindex="8"></select>
<select class="form-control" id="ddCity" runat="server" tabindex="9"></select>
<script type="text/javascript">
$('#ddCountry').on('change', function () {
var storeData = { countryId: this.value }
$.ajax({
type: "POST",
url: "UserRegistration.aspx/GetCities",
data: JSON.stringify(storeData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("The data in list is "+data);
},
error: error
});
});
</script>
My method on .cs page is as follows:
[WebMethod]
public static List<CityBO> GetCities(string countryId)
{
//returning cities
}
The problem is I am able to fetch the data in GetCities method but not able to show it in the ddCity list because it is a HTML control and the method is static, so
ddCity.Items.AddRange(list_of_countries) is not working as ddCity is not being recognized in static method. Please tell how to fill the dropdown list.
You cannot access controls in static method. You need to return list of cities from webmethod and fill dropdown using javascript.In success method of ajax write code like this.
success: function (data) {
fillDropDown(data.d);
}
function fillDropDown(data){
var html = "";
for (var i = 0; i < data.length; i++)
{
html += "<option value='" + data[i].ValueField+ "'>" +
data[i].TextField+ "</option>";
}
$("select[id$=ddlCity]").html(html);
}
You can use ajax success function given below.
success: function (data)
{
var lankanListArray = JSON.parse(data.d);
// running a loop
$.each(lankanListArray, function (index, value)
{
$("#ddlCity").append($("<option></option>").val(this.name).html(this.value));
});
}
i'm new with ajax and i'm trying to call a post action from an ajax method like that
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
window.location.replace('#Url.Content("~/DemandeLocation/MaSelectionOffre")');
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
my post method goes with success but instead of redirectin me to the MaSelection View it return the first view where i call the method, so i tried to put a "Success" fragment in my ajax method and i puted a location replace by "Ma selection" view but i know that the view lose the id so it become null, how can i do it with Ajax,
here my post action for more details
[HttpPost]
[Authorize(Roles = "Locataire")]
public ActionResult MaSelectionOffre(string id)
{
int DemandeLocationGetbyId = Convert.ToInt32(id);
var selectionOffre = db.SelectionOffreLocationSet.Where(model => model.DemandeLocationPublication_ID == DemandeLocationGetbyId).ToList();
return View("MaSelectionOffre", selectionOffre);
}
use json as datatype;
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
dataType:"json",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
window.location.href = msg.redirect;
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
also you need this ;
Convert object to JSON string in C#
If you want redirect page, after ajax call you should use
...
success: function (msg) {
window.location.href = '#Url.Action("MaSelectionOffre", "DemandeLocation")';
},
...
EDIT
If you want replace result, use something like following:
HTML
<div id="updateTargetId">
//table
//tr
//td
//your button that has cssClass buttonSelection
</div>
JS
$(".buttonSelection").click(function () {
selectedId = $(this).parents('tr:first').children('td:first').children('input:first').attr('value');
$.ajax({
// Call MaSelection action method
url: "/DemandeLocation/MaSelectionOffre",
dataType:"json",
data: { id: selectedId },
type: 'Post',
success: function (msg) {
$("#updateTargetId").html(msg);
},
error: function (xhr) {
alert("something seems wrong");
}
});
});
CONTROLLER (return PartialView)
[HttpPost]
[Authorize(Roles = "Locataire")]
public ActionResult MaSelectionOffre(string id)
{
int DemandeLocationGetbyId = Convert.ToInt32(id);
var selectionOffre = db.SelectionOffreLocationSet.Where(model => model.DemandeLocationPublication_ID == DemandeLocationGetbyId).ToList();
return PartialView("MaSelectionOffre", selectionOffre);
}
i changed my action to a get action and in my button i just added window.location.replace with link and ID
<button type="button" class="buttonSelection" onclick="window.location.replace('#Url.Content("~/DemandeLocation/MaSelectionOffre?id="+item.Publication_ID)')"> <span class="ui-icon ui-icon-cart"></span> </button>
I'm using C# asp.net mvc.
I wrote a Ajax function in my Home controller - > index.cshtml.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'html',
url: '#Url.Action("getAlerts","Home")',
data: ({}),
success: function (data) {
$('#alertList').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
</script>
this is my function in Home controller
public IList<tblInsurance> getAlertsIns()
{
var query = (from i in db.tblInsurances
where i.status == true && i.EndDate <= DateTime.Today.AddDays(7)
select i).ToList(); ;
return query;
}
public string getAlerts()
{
string htmlval = "";
var InsExpirList = getAlertsIns();
if (InsExpirList != null)
{
foreach (var item in InsExpirList)
{
htmlval += item.tblContractor.Fname + " " + item.EndDate + "<br />";
}
}
return htmlval;
}
But ther is error and it says " The resource cannot be found."
POST http://localhost:49368/Home/getAlerts 404 Not Found
what is wrong with my code?
If you want your controller action to accept POSTs, you must decorate it with an attribute specifying that fact:
[HttpPost]
public string getAlerts()
{
// ...
}
In this case, however, it seems like a GET request would be more appropriate (your action is called getAlerts after all). If that's the case you can omit the accepted verb, or use [HttpGet] instead. You would also have to change your AJAX request:
$.ajax({
type: 'GET',
dataType: 'html',
url: '#Url.Action("getAlerts","Home")',
/* ... */
});
I'm having a problem trying to get a ViewBage property value and pass it into a jQuery method.
For example, in my code below, #ViewBag.CountResult have the value 1, and it is displayed in my browser, but when passed into the updateResultFooter method, it is like "" ! Don't get why. Down is my view. Any help ?
Thanks in advance
<div>
<div>
<span>Téléphone ?</span>
<input id="idTxTel" type="text" name="txTelephone"/>
<input id="idBnSearch" type="submit" value="Chercher" name="bnSearch"/>
</div>
#Html.Partial("_Result", Model)
</div>
<script type="text/javascript">
var methodUrl = '#Url.Content("~/Search/GetReverseResult/")';
$(document).ready(function (){
updateResultFooter("#ViewBag.CountResult", "#ViewBag.PageNumber", "#ViewBag.PageCount");
$("#idBnSearch").click(function (){
var telValue = $("#idTxTel").val();
pageIndex = 0;
doReverseSearch(telValue, pageIndex, methodUrl);
updateResultFooter("#ViewBag.CountResult", 0, "#ViewBag.PageCount");
});
$("#bnNextPage").live("click", function (){
var telValue = $("#idTxTel").val();
pageIndex = pageIndex + 1;
doReverseSearch(telValue, pageIndex, methodUrl);
updateResultFooter("#ViewBag.CountResult", pageIndex, "#ViewBag.PageCount");
});
});
function updateResultFooter(resultCount, pageIndex, pageCount){
if (resultCount == '0')
$("#resultFooter").hide();
else
{
$("#resultFooter").show();
if (pageIndex == 0)
$("bnPreviousPage").attr('disabled', 'disabled');
else
$("bnPreviousPage").removeAttr('disabled');
if ((pageIndex + 1) == pageCount)
$("bnNextPage").attr('disabled', 'disabled');
else
$("bnNextPage").removeAttr('disabled');
}
}
function doReverseSearch(telValue, pageIdx, methodUrl){
$.ajax({
url: methodUrl,
type: 'post',
data: JSON.stringify({ Telephone: telValue, pageIndex: pageIdx }),
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#result').replaceWith(data);
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
}
</script>
PS: I'm using this code to modify the display of the web page, depending on the result of a search made by the user.
I've changed the approach I was using. Now, I've changed my model so it contains the data I want to display, like (CountResult, PageCount). And it works fine now.