Ajax jquery passing multiple parameters web services - c#

<script type="text/javascript">
$('#btnregister').click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "fetchusers.asmx/RegUsers",
data: "{ username: '" + $("#txtuser").val() + "name: '" + $("#txtname").val() + "'}",
dataType: "json",
success: function (data) {
alert("Successfully register");
$("#btnregclose").click();
}
});
});
</script>
<div id="registration">
<fieldset>
<legend>Registration Form</legend>
<input id="txtuser" type="text" placeholder="Username" /><br />
<input id="txtname" type="text" placeholder="Name" /><br />
<input id="txtpass" type="password" placeholder="password" /><br />
<input id="txtconfirmpass" type="password" placeholder="confirm password" /><br />
<input id="btnregister" type="button" value="Register" />
<input id="btnregclose" type="button" value="close" />
</fieldset>
</div>
[WebMethod]
public string RegUsers(string username, string name)
{
string response = username + name;
return response;
}
I'm a beginner in Ajax Jquery and I'm doing exercise to improve my knowledge about it. My problem is when I click #btnregister it's not working. I think there's a problem in the parameters I passed on the ajax but I don't know what is it.

try this :
$(document).ready(function () {
$('#btnregister').click(function () {
var obj = { username: $("#txtuser").val(), name: $("#txtname").val() };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "fetchusers.asmx/RegUsers",
data: JSON.stringify(obj),
dataType: "json",
success: function (data) {
alert("Successfully register");
$("#btnregclose").click();
}
});
});
});
this worked in my local enviroment.

Instead of trying to build the string by concatination it might be easier to do something like this:
$.ajax(url, {
data: JSON.stringify({
username: $("#txtuser").val(),
name: $("#txtname).val()
})
});
It will prevent typos/problems that might occur if you have say, a comma, in one of your fields. Note though, that ie7 and lower will require you to include a file called json2.js (github).
Edit:
Also, try executing your web service manually (just browse to the url, use a poster, etc). It is entirely possible you are getting a 404, or a server error.
Edit part 2: A good way to debug ajax issues in firefox is to use ctrl-shift-k to open the web console. Make sure "Net" is enabled and that "Log Request and Response Bodies" is checked in its dropdown. This way you can see the requests going out and coming back. If you dont see one then its an issue with your javascript, not the ajax.
Another Edit:
Also, I see your click event isnt in a $(document).ready(function() {}); It could be that you are attaching the click event before the button is rendered. Therefore the event isnt attached and your not even executing the ajax code.

use this syntax....
data: "{ 'username': '" + $("#txtuser").val() + "', 'name': '" + $("#txtname").val() + "'}",

The code in the question is right it needs simple solution. Go to yourwebservice.asmx.cs file and uncomment the following line given at class level this will resolve the issue of calling this webservice from jQuery or Ajax.
[System.Web.Script.Services.ScriptService]

Related

receiving error (internal server error) when sending Ajax request on Asp.NET Web Forms Endpoint

I am sending ajax request in asp.net i get this error
POST http://localhost:1549/AdminArea/Roles.aspx/Create 500 (Internal
Server Error)
it is with Master Page Also shown code is in individual page Roles.aspx
my HTML Code
<form id="FormSave">
<input type="text" name="txtName" id="txtName" required="required"
class="form-control"/>
<input type="radio" name="Status" value="1" checked="checked"/> Active
<input type="radio" name="Status" value="0"/> In-active
</form>
Javascript Code For Sending Request
<script type="text/javascript">
$(document).ready(function () {
$("#BtnSave").click(function () {
var jsonText = JSON.stringify({ Name: $("txtName").val(), Status: $("Status").val() });
$.ajax({
type: "POST",
url: "Roles.aspx/Create",
contentType: "application/json; charset=utf-8",
data: jsonText,
dataType: "json",
success: function (response) {
alert(response);
}
});
});
});
</script>
SERVER SIDE C# SCRIPT /// IN Roles.aspx.cs file
[WebMethod]
public static string Create(string Name, string Status)
{
return "Hello " + Name + "With " + Status;
}
I want to alert this Hello Name With Status

Why is ajax call to webmethod returning 401 from code behind?

ajax
function verify() {
$.ajax({
type: "POST",
url: "Register.aspx/verifyImage",
data: '{text: "' + $("#<%=TextBox4.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d)
},
failure: function(response) {
alert(response.d);
}
});
}
C# webmethod
[WebMethod]
public void verifyImage(string text)
{
string imageString = Session["imageString"].ToString();
if (imageString.Equals(text))
{
Response.Write("<script>alert('Memeber Page');</script>");
}
else
{
Response.Write("<script>alert('Incorrect');</script>");
}
}
Page controls
<div style="height: 50px">
<asp:Image ID="Image1" runat="server" />
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<input id="Button1" type="button" value="Submit" onclick="verify()"/>
</div>
Debug Output
"name":"POST /Register.aspx/verifyImage","duration":"00:00:00.0161020","success":true,"responseCode":"401","url":"http://localhost:54506/Register.aspx/verifyImage","properties":{"DeveloperMode":"true","_MS.ProcessedByMetricExtractors":"(Name:'Requests', Ver:'1.0')
I'm new to ajax and am building an image verifier page. I want to compare the image text to asp textbox text using ajax to send the textbox text to a web method in the code behind. In the output, the ajax call writes success: true, but returns a 401 (unauthorized) code. What am I doing wrong? At this point I'm just trying to get the call to work and will fill in the webmethod more later.

Error submitting form data asp.net MCV [duplicate]

This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 6 years ago.
I'm new to front-end development and i'm trying to get a better understanding of front-end and how it connects with the back-end. Basically I am trying to submit a file to an action method in the back-end but for some reason it never hits the method.
Front-end:
<form id="Form2" name="Form2">
<input type="file" name="file" id="file" multiple />
<input type="submit" value="Upload" />
</form>
<script>
$(function () {
$("#Form2").submit(function (event) {
var formData = new FormData(this);
$.ajax({
url: "Property/UploadPropertyCSV",
type: 'POST',
datatype: 'json',
data: formData
}).done(function (data) {
alert(data);
});
});
});
</script>
Back end:
public ActionResult UploadPropertyCSV(HttpPostedFileBase file)
{
// bunch of processing
return Json(true);
}
Any ideas why this is happening?
Thanks in advance
im not really sure about your ajax method, but basically, I would do it like bellow :
$("#Form2").submit(function (event) {
var formData = new FormData(this);
$.ajax({
url: '#Url.Action("UploadPropertyCSV", "Property")',
type: 'POST',
datatype: 'json',
data: { file: formData},
success: function (result) {
alert(result);
}
})
});

Second cascading dropdown knockout not setting with returned value

I'm having an issue with a dropdown list using Knockout. I'm fairly new to this. The scenario is that when I edit some data, I call a Web Api to return some information in JSON. The JSON is then mapped and displayed for an end user to edit if they wish to. I have two dropdown lists (manufacturers and ranges). The manufacturer dropdown list gets populated and set to the correct value which is returned. The issue is that the second dropdown list gets populated but does not get set to the correct value. Instead it remains at the default "select" value. Would someone be able to explain why this happens or point me in the right direction?
My code is as follows. I have trimmed it down but can provide any further code if need be. Many thanks.
JS
/// <reference path="../knockout/knockout-3.4.0.debug.js" />
/// <reference path="../jquery/jquery.min.js" />
var deal = function () {
var self = this;
// These are the initial options
self.ManufacturerOptions = ko.observableArray();
self.VehicleManufacturerId = ko.observable();
self.RangeOptions = ko.observableArray();
self.VehicleRangeId = ko.observable();
var Deals = {
ManufacturerOptions: self.ManufacturerOptions,
VehicleManufacturerId: self.VehicleManufacturerId,
RangeOptions: self.RangeOptions,
VehicleRangeId: self.VehicleRangeId,
};
self.Deal = ko.observable();
self.Deals = ko.observableArray();
RetrieveDeals();
GetManufacturers();
self.EditData = function (Deal) {
GetManufacturers();
GetRanges(Deal.VehicleManufacturerId);
self.Deal(Deal);
};
function GetManufacturers() {
$.ajax({
url: 'http://localhost:47633/api/Vehicle/GetManufacturers',
type: 'get',
crossDomain: true,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (dataReturned) {
self.ManufacturerOptions(dataReturned);
}
});
}
function GetRanges(manufacturerId) {
$.ajax({
url: 'http://localhost:47633/api/Vehicle/GetRanges?manufacturerCode=' + manufacturerId,
type: 'get',
crossDomain: true,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (dataReturned) {
self.RangeOptions(dataReturned);
}
});
}
};
$(document).ready(function () {
ko.applyBindings(new deal());
});
ASCX Control
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Home.ascx.cs" Inherits="Desktop.Controls.DealBook.Home" %>
<h1>DealBook</h1>
<div data-bind="if: Deal">
<div>
<h2>Update Deal</h2>
</div>
<div>
<p>Manufacturer: <select id="Manufacturer" data-bind="options: ManufacturerOptions, optionsCaption: 'Select Manufacturer', optionsValue: 'cman_code', optionsText: 'cman_name', value: Deal().VehicleManufacturerId, event: { change: manufacturerChanged}"></select></p>
<p>Range: <select id="Range" data-bind="options: RangeOptions, optionsCaption: 'Select Range', optionsValue: 'cran_code', optionsText: 'cran_name', value: Deal().VehicleRangeId, event: { change: rangeChanged }"></select></p>
</div>
<input type="button" id="btnUpdateData" class="btn btn-primary" value="Update Deal" data-bind="click: UpdateData" />
<input type="button" id="btnCancel" class="btn btn-primary" value="Cancel" data-bind="click: Cancel" />
UPDATE
I believe the issue is that my code is trying to update the dropdown list to the selected value before the options are returned from the Web API. Any thoughts on how I can bind the value to the deal once the options are returned?
Fixed by using Jquery promises to defer method calls until complete.
I now call $.when(GetRanges(Deal.VehicleManufacturerId)).then(function () { self.Deal(Deal) }); instead of
GetRanges(Deal.VehicleManufacturerId);
self.Deal(Deal);

Client side validation using Data Annotations

I am having a problem using client side validation in combination with Data Annotations.
The project is using ASP.NET Framework 4.5, a Web Application with the MVP pattern and jQuery Ajax calls to dynamically load user controls.
This is the (stripped) user control which contains the input element that needs to be validated:
<form id="insertArtist" class="form-horizontal">
<fieldset>
<legend>Add new artist</legend>
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<asp:TextBox runat="server" ID="name" ClientIDMode="Static" CssClass="input-medium"></asp:TextBox>
<ml:DataAnnotationValidator runat="server" ID="davName" ControlToValidate="name" EnableClientScript="true" PropertyToValidate="Name" SourceTypeName="Music.Library.Domain.Models.Artist, Music.Library.Domain">
</ml:DataAnnotationValidator>
</div>
<div class="form-actions">
<button id="save" class="btn btn-primary" name="submit" type="submit">Save</button>
<button id="cancel" class="btn">Cancel</button>
</div>
</div>
</form>
This user control get's dynamically loaded using the following ajax call:
$('#add').click(function () {
$.ajax({
url: "/Artist/Manage/Insert.ascx.axd",
type: "POST",
dataType: "html",
success: function (obj) {
$('#body_artist').html($(obj));
}
});
});
This is the jquery executed when a user clicks save:
$('#save').click(function (event) {
event.preventDefault();
$.ajax({
url: "/artist/add.axd",
type: "POST",
dataType: "html",
cache: false,
async: true,
data: 'Ajax=true&' + $('#insertArtist').serialize(),
beforeSend: function (jqXHR, settings) {
$('#loading').show();
},
success: function (data) {
if (data == "succes") {
showNotification('succes', 'Succesfully added artist');
} else {
showNotification('error', 'Error while adding artist: ' + data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
showNotification('error', 'Error while adding artist: ' + data);
},
complete: function () {
$('#loading').hide();
}
});
});
Now, since there is no trigger from an asp.net control the custom data annotation validator will not validate.
I've tried validating using Javascript, using the Page_ClientValidate(), ValidateEnable() and Validate() methods. Unfortunately when trying this I keep getting the same error over and over:
Page_ClientValidate is not defined
Same story for the other methods.
I'm at wits end here.
Is it because the UserControl is dynamically loaded that these client validation methods do not work? I've set EnableClientScript to true.
Or does anyone have another idea on how to implement this? I'd really like to use the Data Annotations.
Thanks in advance!
It can be a solution
http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/
Especially, it is a dublicate of this question Unobtrusive validation not working on dynamically-added partial view which also refers to XHalent blog

Categories

Resources