I have a ASP textbox of class clsArtistList placed inside a usercontrol
<asp:TextBox CssClass="clsArtistList" ID="txtArtistList" runat="server"></asp:TextBox>
Then I use jquery-ui-1.8.16 to create the autocomplete feature for my textbox. I copied it from http://www.dotnetcurry.com/ShowArticle.aspx?ID=515 but I don't really know how it works
$(".clsArtistList").autocomplete({
source: function(request, response) {
$.ajax({
url: "../ArtistWS.asmx/GetAllArtists",
data: "{ 'ARTIST_NAME': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.ARTIST_NAME
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
},
minLength: 1
});
and this is my web service
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<Artist> GetAllArtists(string ARTIST_NAME) {
ArtistCollection coll = ArtistManager.GetAllArtists();
return coll.FindAll(a => a.ARTIST_NAME.ToLower().StartsWith(ARTIST_NAME.ToLower()));
}
For your interests, my ArtistCollection is a List of artist. And an Artist class looks like this:
public class Artist {
public string ARTIST_ID { get; set; }
public string ARTIST_NAME { get; set; }
public string ARTIST_NATIONALITY { get; set; }
public string ARTIST_INFO { get; set; }
}
But the code does not work. Each time i type, I recieve a message alert Internal Server Error
Thank you in advance. I need you helps
If you receiver a server error message, I would assume the problem is not in the javascript, but somewhere on your server.
Did you try to debug your ASP webservice code?
I think the problem may be the value you are setting url to.
Try removing the ".." from the call
$.ajax({
url: "/ArtistWS.asmx/GetAllArtists",
Related
I have written a POST request that accepts my Model but once I get into the request the List is returning null.
I have read multiple solutions online from adding [FormBody] to checking my naming conventions but nothing seems to work correctly.
In my Script I create an Array var UserPermissions = new Array();
I then push to the array multiple objects:
var permission = {
UserId: #Model.UserId,
AppId: #Model.AppId,
PermissionId: this.value
}
UserPermissions.push(permission);
Then I perform my Ajax request:
$.ajax({
url: '#Url.Action("UpdateUserPermissions")',
data: JSON.stringify(UserPermissions),
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (status) {
swal("User Permissions have been updated.", { icon: "success" });
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error updating permissions, please contact support.");
}
});
My Controller POST Request Looks like this:
public IActionResult UpdateUserPermissions([FromBody]PermissionPartialModel model)
{
return View();
}
In every case [FromBody]PermissionPartialModel model is returning null when it should be returning a list.
Here is my Model:
public class PermissionPartialModel
{
public int AppId { get; set; }
public int UserId { get; set; }
public List<UserPermissionsModel> UserPermissions { get; set; }
}
What could be causing this and what is a solution to fix this?
var UserPermissions= {
UserId: #Model.UserId,
AppId: #Model.AppId,
PermissionId: this.value
}
//UserPermissions.push(permission);
$.ajax({
url: '#Url.Action("UpdateUserPermissions")',
data: UserPermissions,
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (status) {
swal("User Permissions have been updated.", { icon: "success" });
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error updating permissions, please contact support.");
}
});
You are sending an array from view but receive object in controller. You need to change your parameter type from object to list
public IActionResult UpdateUserPermissions([FromBody]List<PermissionPartialModel> model)
{
return View();
}
This will map but you will get UserPermissions null. To solve this you need to make changes in PermissionPartialModel and permission object in view.
permission
var permission = {
UserId: 2,
AppId: 2,
UserPermissions: { PermissionId: 2 }
}
UserPermissions.push(permission);
PermissionPartialModel
public class PermissionPartialModel
{
public int AppId { get; set; }
public int UserId { get; set; }
public UserPermissionsModel UserPermissions { get; set; }
}
My controller:
[HttpPost]
public IActionResult UserRoleChanged(string roleName,string userName)
{
var a = roleName;
var b = userName;
return RedirectToAction("UserManager");
}
Script in view:
if (window.confirm('Are you sure that you want to change role?')) {
jQuery.ajax({
type: "POST",
url: "#Url.Action("UserRoleChanged", "DashBoard")",
dataType: 'json',
data: { 'roleName': this.text, 'userName': 'SomeName'},
cache: false,
success: function (data){
window.location.href = data;
},
failure: function (data) {
}
})};
When I run script above UserRoleChanged action does not invoke. If I try to remove userName variable from data in ajax then UserRoleChanged action method invokes without any problem. How can i pass multiple data to my controller? What is wrong with my code?
Remove the dataType: 'json' from the ajax, and try again. As you are trying to get the values on server side as normal variable, so dataType: 'json' is not required here.
You can create a model with same properties and pass it as a parameter. Its a good practice.
Looks like this.
public class User
{
public string RoleName { get; set; }
public string UserName { get; set; }
}
And the json looks like this example
{
"RoleName" : "somename",
"UserName" : "somename"
}
I'm trying to send a list of products for my web api in C# via JavaScript but my API doesn't accepts the products. How do I should pass it?
This is my model
public class ProductModels
{
public int productId { get; set; }
public string description { get; set; }
public int quantity { get; set; }
public decimal amount { get; set; }
}
and my API endpoint
[Route("api/pag_seguro/transactions/credit_card")]
public IHttpActionResult DoTransactionWithCreditCard(ProductModels[] products, string senderHash, string cardHash)
in Javascript I'm trying to send it like this
data.products = [{ "productId": 1, "description": "tupperware", "quantity": 1, "amount": 29.80 }];
$.ajax({
type: 'POST',
url: url + '/api/pag_seguro/transactions/credit_card?cardHash=' + cardHash + '&senderHash=' + senderHash,
data: data,
success: function (response) {
console.log(response);
},
dataType: 'json',
async: false
});
and still about this endpoint... how do I send the senderHash and cardHash as POST parameters so that than doesn't appears in web url?
Thank you all
You need to set the content type in the request as
contentType:"application/json"
Also, use JSON.stringify to convert the data to JSON format when you send.
Try this code:
$.ajax({
type: 'POST',
url: url + '/api/pag_seguro/transactions/credit_card?cardHash=' + cardHash + '&senderHash=' + senderHash,
data: JSON.stringify(data),
contentType: "application/json",
success: function (response) {
console.log(response);
},
dataType: 'json',
async: false
});
try this
public IHttpActionResult DoTransactionWithCreditCard([FromUri] SiteInfo, siteInfoProductModels[] products)
and your siteinfo model is
public class SiteInfo
{
public string senderHash { get; set; }
public string cardHash { get; set; }
}
finally remove your route from action header and add new route in webapiconfig.cs like this (and change js file set params liek this /param1/param1 )
config.Routes.MapHttpRoute(
name: "HashRoute",
routeTemplate: "api/{controller}/{action}/{senderHash}/{cardHash}"
);
Im trying to stringify a javascript object and then pass the string as a parameter to a WebMethod in Code Behind. I can't get it to work as I get a Internal Server Error of 500 and the stacktrace says that value is missing for parameter.
Here is the javascript code:
var jSon = JSON.stringify(javascriptObject);
// "{"Foretagsnamn":"Avector","BGFarg":"000000","TextColor":"fafafa","FooterFarg":"ffffff","FooterColor":"000000","FooterLinkColor":"050505","FeaturedBorderColor":"","HoverFarg":"12ebeb","RutFarg":"0d0d0d","SelectedRutFarg":"","RutColor":"FFFFFF","LankColor":"","DelaMedSig":"1","PersonalSida":"0","StartpageTitle":"","StartpageDescription":"","GoogleMaps":"<iframe width=\"425\" height=\"350\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"https://maps.google.se/maps?f=q&source=embed&hl=sv&geocode=&q=Avector AB&aq=&sll=56.225986,12.870827&sspn=0.076248,0.154324&ie=UTF8&hq=Avector AB&hnear=&t=m&cid=645910733081021950&iwloc=A&ll=56.224594,12.859229&spn=0,0&output=embed\"></iframe><br /><small>Visa större karta</small>","HittaKartaUrl":"http://www.hitta.se/avector ab/ängelholm/hxTP-4v1HG?vad=Avector AB","EniroKartaUrl":"http://kartor.eniro.se/m/aKkhi","Ikoner":"2","Email":"info#avector.com","AdressSida":"1","shadowColor":"ffffff","lineColor":"2b292b","MenuHoverIcon":"Välj bild från server","fontFamily":"Verdana","supportText":"Support Avector","captcha":true,"metaKeywords":"","ShowSupportInFooter":true}"
$.ajax({
type: "POST",
url: "Post/Installningar.aspx/Updatera",
data: jSon,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var resultAsString = result.d;
//_this.parent().siblings('.SavedStatus').html(resultAsString);
if (resultAsString == "1") { // Gick bra att spara.
alert("Uppgifterna är sparade.");
document.location = document.location;
}
else {
$('#StatusText').html("Gick inte att spara uppgifterna.");
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
And here Is the webmethod:
[WebMethod]
public static string Updatera(string jSon)
{
It feels like I've tried everything that I've found when searching by google and here on SO.
I've also tried this guide that many refer to: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Any ideas?
First, you need to use:
var jSon = JSON.stringify({obj:javascriptObject});
instead of:
var jSon = JSON.stringify(javascriptObject);
Then your WebMethod would be like:
[WebMethod]
public static string Updatera(aData obj)
{
// logic code
}
Now here aData is your class something like below :
public class aData {
public string Foretagsnamn { get; set; }
public string BGFarg { get; set; }
public string TextColor { get; set; }
public string FooterFarg { get; set; }
public string Email { get; set; }
}
So your final code look like
jQuery:
var jSon = JSON.stringify({ obj:javascriptObject });
$.ajax({
type: "POST",
url: "Post/Installningar.aspx/Updatera",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response){
// Do something
}
function OnErrorCall(){
// Do something
}
Code Behind:
public class aData {
public string Foretagsnamn { get; set; }
public string BGFarg { get; set; }
public string TextColor { get; set; }
public string FooterFarg { get; set; }
public string Email { get; set; }
}
[WebMethod]
public static string Updatera(aData obj)
{
// Logic code
}
Use this format for ajax post format :
var jSon = JSON.stringify(javascriptObject);
Your Json Format will be like this :
'{name: "' + name +'" }',
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Installningar.aspx/Updatera",
data: jSon;
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
Follow this step for complete run your code :
http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
I am sending data from from a javascript app to a MVC5 controller, however when data is submitted to the Submit controller action, it is never called. I have some very simple mappers which create the following JSON object:
function mapContactDto(vm)
{
var contactDto = {};
contactDto.firstName = vm.firstName();
contactDto.lastName = vm.lastName();
contactDto.companyName = vm.companyName();
contactDto.emailAddress = vm.emailAddress();
contactDto.phonePrimary = vm.phonePrimary();
contactDto.phoneSecondary = vm.phoneSecondary();
contactDto.address1 = vm.address1();
contactDto.address2 = vm.address2();
contactDto.city = vm.city();
contactDto.postalCode = vm.postalCode();
contactDto.country = vm.country();
return contactDto;
}
function mapCartItems(vm)
{
var cartItemsDto = new Array();
$.each(vm.selectedOptions(), function (index, step, array) {
var sku = step.selection().sku;
if (sku !== "0") {
cartItemsDto.push(sku);
}
});
return cartItemsDto;
}
/* if i dump the object that is sent to the server with `console.log(JSON.stringify(item))` I get:
{
"skus": ["1001","8GB","201"],
"contact": {
"firstName":"Jon",
"lastName":"Doe",
"companyName":"Yup my company",
"emailAddress":"contact#me.com",
"phonePrimary":"012111 231",
"phoneSecondary":"",
"address1":"1 Billing Way",
"address2":"Navigation House",
"city":"London",
"postalCode":"112211",
"country":"GB"
}
}
*/
I then send the data with the following code:
var contactDto = mapContactDto(self.billingVm());
var cartItemsDto = mapCartItems(self.configurationVm());
var req = new XMLHttpRequest();
req.open('HEAD', document.location, false);
req.send(null);
var item = {
skus: mapCartItems(cartItemsVm()),
contact: mapContactDto(billingVm())
};
var url = '/Knockout/Submit';
$.ajax({
cache: false,
url: url,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: item,
type: 'POST',
success: function (data, textStatus, jqXHR) {
},
error: function (data, textStatus, jqXHR) {
}
});
My controller code is below:
public JsonResult Submit(string[] Skus, ContactDto Contact)
{
return Json(new { success = true, message = "Some message" });
}
/* and MVC models are: */
public class ContactDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string CompanyName { get; set; }
public string EmailAddress { get; set; }
public string PhonePrimary { get; set; }
public string PhoneSecondary { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
I have the following questions please:
Submit is never called however, if I comment out the controller parameters so it becomes Submit() then it is called, why is this?
From the above, it seems like the controller framework cannot match up the parameters - any idea what I am doing wrong please?
How to enable debugging on the MVC controller so I can see what's going on?
Four things you must check using ajax calls,
1. If using javascript object you must stringify the object before passing.
2. The Action verb for the action method should be same as the type of your ajax call if POST then the action method should be decorated by action verb [HttpPost].
3. Always use the relative path for url's in ajax as #Url.Action("action", "controller").
4. The input parameters of your action method method should match the json object parameters (exactly i.e. case sensitive).
For debugging you may use firebug addon in your browser so that you can see what is sent over the network or press F12 for debugging tool in that check in network tab.
You will have to make two changes:
Stringify your Json as below:
$.ajax({
cache: false,
url: url,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(item),
type: 'POST',
success: function (data, textStatus, jqXHR) {
},
error: function (data, textStatus, jqXHR) {
}
});
Second, Just Annotate your Method with [HttpPost] as below:
[HttpPost]
public JsonResult Submit(string[] Skus, ContactDto Contact)
{
return Json(new { success = true, message = "Some message" });
}