Pass data from html form to c# webservice using ajax - c#

I have a form html made using bootstrap in phpstorm, and I want to pass the information to a c# webservice using ajax.
Bust I have some doubts in what to put in the ajax url (represented bellow).
This is my html/bootstrap form:
<form role="form" action="" method="post" class="login-form">
<div class="form-group">
<label class="sr-only" for="form-username">Email</label>
<input type="text" name="form-username" placeholder="Email....." class="form-username form-control" id="form-email">
</div>
<div class="form-group">
<label class="sr-only" for="form-text">Type Order</label>
<input type="text" name="order" placeholder="Tipo Encomenda" class="form-text form-control" id="textbox1">
</div>
<span id="spnGetdet" style="font-size:x-large" />
<div class="form-group">
<label class="sr-only" for="form-number">Number</label>
<input type="number" min="0" max="150" name="orderQuantity" placeholder="Numero Peças" class="form-number form-control" id="form-number">
</div>
<div class="form-group">
<label class="sr-only" for="form-radio">Urgente</label>
<label class="radio-inline">
<input type="radio" name="optradio">Urgente</label>
<label class="radio-inline">
<input type="radio" name="optradio">Não Urgente
</label>
</div>
<button type="submit" class="btn btn-primary" id="submitOrder">Enviar</button>
</form>
And this is my ajax/jquery code:
<script type="text/javascript">
$("#submitOrder").click(function(){
$(document).ready(function () {
var TextBox1 = $("#textbox1");
TextBox1.change(function (e) {
var Name = TextBox1.val();
if (Name != -1) {
Getdet(Name);
}else {
<?php echo "erro"?>;
}
});
});
}
function Getdet(Name) {
$.ajax({
type: "POST",
url: "",
data: "{'Custname':'" + Name + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response){
$("#spnGetdet").html(response.d);
},
failure: function (msg)
{
alert(msg);
}
});
}
</script>
And the last my c# webservice (this is a test, and i only want to collect the type of the order):
[WebMethod]
public String GetCustdet(string Custname)
{
return Custname;
}
So, if i have the project(website) made in phpstorm and webservice visual studio, what do I have to put in the url of ajax to reach the web service???
P.S: WebSite running in xampp

I'm assuming that, you are using MVC pattern I have given following url. You should replace controller name in [controller] place. You should replace localhost:5566 in or whatever in to [server-name].
option 1: [GET] http://[server-name]/[controller]/GetCustdet?Custname=Jhon
without data.
option 2: [POST] http://[server-name]/[controller]/GetCustdet
with data: '{Custname:"Jhon"}'
Otherwise, If you are using Asp.Net template to create the WebMethod then you should use the aspx page name in place the of [controller].
Alternatively, you have Route configurations to customize the URL and the data.

Related

Posting JSON data via AJAX to Web API fails with "The JSON value could not be converted to System.Int32"

I want to send data from my website to my WEB API my partners are working on via AJAX. The WEB API is a .net Core 3.0 app. And the form is to register a new user.
But I'm facing a problem from parsing the input data of one of my input fields.
My JQuery script looks like this:
<script type="text/javascript">
$(document).ready(function () {
$("#postform").submit(function (e) {
e.preventDefault();
var apiurl = "https://luna.example.com:44350/login/register";
var data = {
Name: $("#fullName").val(),
CPRNumber: $("#cprNumber").val(),
Email: $("#Email").val(),
Password: $("#PasswordValidated").val(),
ZipCode: $("#zipCode").val(),
}
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: 'POST',
url: apiurl,
data: JSON.stringify(data),
dataType: 'json',
success: function (d) {
alert("Saved Successfully");
document.getElementById("postform").reset();
},
error: function (request) {
alert("Error please try again");
alert(request.responseText);
}
});
});
});
Form Code looks like this:
<form id="postform">
<div class="form-group">
<label for="fullName">Name</label>
<input type="name" class="form-control" id="fullName">
<small>Geben Sie Ihren ganzen Namen ein (Vor + Nachname)</small>
</div>
<div class="form-group">
<label for="cprNumber">CPR Nummer</label>
<input type="text" class="form-control" id="cprNumber">
<small>Geben Sie Ihre Dänische CPR Nummer ein</small>
</div>
<div class="form-group">
<label for="zipCode">Postleitzahl</label>
<input type="number" class="form-control" id="zipCode">
<small>Geben Sie Ihre Postleitzahl ein</small>
</div>
<div class="form-group">
<label for="Email">Email addresse</label>
<input type="email" class="form-control" id="Email" aria-describedby="emailHelp">
<small id="emailHelp" class="form-text text-muted">Deine Email wird nicht mit anderen geteilt</small>
</div>
<div class="form-group">
<label for="Password1">Passwort </label>
<input type="password" class="form-control" id="Password1">
<small>(minimum 8 Zeichen)</small>
</div>
<div class="form-group">
<label for="RepeatPassword">Passwort erneut eingeben (Bestätigen)</label>
<input type="password" class="form-control" id="RepeatPassword">
</div>
<button type="submit" class="btn btn-primary">Registrierung abschließen</button>
</form>
If I now hit the "submit" button I will get the following message back from my WebAPI:
errors":{"$.ZipCode":["The JSON value could not be converted to System.Int32. Path: $.ZipCode
Hardcoding the zipcode will succeed and the data will be stored in the database
{
Name: $("#fullName").val(),
CPRNumber: $("#cprNumber").val(),
Email: $("#Email").val(),
Password: $("#PasswordValidated").val(),
ZipCode: 6400,
}
Trying to use
ZipCode: $("#zipCode").val().parseInt
Will prevent the error message, but the value should now be undifiened and thats what the server will return as a new error message. Value undifined (as expected) and Foreign Key missmatch (can be ignored, because value undifiened)
Output of "data" (without json.stringify):
console.log(data);
prints:
{Name: "", CPRNumber: "", Email: "", Password: "", ZipCode: "6400"}
Output of data using json.stringify:
alert(JSON.stringify(data));
{"Name":"","CPRNumber":"","Email":"","Password":"","ZipCode":"6400"}
Without the json.stringify I get following error msg:
{"type":"https://www.rfc-editor.org/rfc/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|eb442172-4475b7c4c9eb631c.","errors":{"$":["'N' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."]}}
I'm pretty sure this is because the "" quotes are missing in the one without json.stringify. But adding quotes manually will result in the same error.
Is there a smart way, to fix that problem ? Because hardcoding the value seems working fine, but getting the value from the inputfield fails. I guess it's because of "" Quotes that are getting added.
Please use parseInt($("#zipCode").val()) to convert to integer.
OR
Modify your form zipCode input element type to number from text (<input type='number' name='zipcode' id='zipcode'>)

AJAX parameter still null

I have a simple modal form used to insert data; when i submit data, i correctly go to my method but the parameter still null value.
This is my Razor code:
<form id="SaveKeyForm" asp-page-handler="SaveExternalKEY" data-ajax="true" data-ajax-method="post">
<div class="modal-body">
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<div class="form-group">
<label asp-for="wItem.Guid"></label>
<input asp-for="wItem.Guid" name="GUID" class="form-control" id="modalCustomerGUID" readonly required />
<span asp-validation-for="wItem.Guid" class="text-danger"></span>
</div>
<div class="form-group">
#Html.Hidden("External_Key_Type_ID", "")
<select class="custom-select mr-sm-2" asp-items="_KeyOptions" name="Selected_Key_Type_ID"><option selected>Choose</option></select>
</div>
<div class="form-group">
<label asp-for="wExternal_ID.ExternalKey"></label>
<input asp-for="wExternal_ID.ExternalKey" name="ExternalKEY" class="form-control" required/>
<span asp-validation-for="wExternal_ID.ExternalKey" class="text-danger"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" id="saveKey" class="btn btn-primary">Save</button>
</div>
This is my JS code:
$("#saveKey").click(function (e) {
e.preventDefault();
console.log('Ajax submit');
var form = $(this).parents('.modal').find('form');
var formAction = form.attr('action');
var fdata = form.serialize();
console.log(fdata);
var sdata = { GUID: 'fdsfas' };
$.ajax({
type: 'post',
url: formAction,
data: sdata,
dataType: "text",
processData: false,
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
statusCode: {
404: function () {
console.log("page not found");
},
200: function () {
console.log("Status Ok");
}
}
}).done(function (result) {
console.log('Result: ' + result);
});
});
and this is my method:
public IActionResult OnPostSaveExternalKEY(string GUID)
{
try
{
return new OkResult();
}
catch (Exception ex)
{
return new StatusCodeResult(404);
}
}
}
i have try to:
- pass data as 'fdata' variable: still null
- pass fixed data as 'sdata' variable: still null
- try to Json serialize: still null
If i use jquery-ajax-unobtrusive, i can pass correctly value to my method, but i cannot manage error message in modal form and url change.
Thanks for any help.

Jquery form submit() to the action in the controller then returns an object to the client and not reload page

I want after I call the submit() function in jQuery. It will go to action to process the logic, then the action will return an object to the client, so the client displays it.
I tried many ways but no, please help me.
I have a form like this:
<form action="/Mycontroller/Save" id="myform" enctype="multipart/form-data" method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
</form>
<button class="btn btn-success" type="button" onclick="Save()">Save</button>
I want to try Code Js:
function Save(
$("#myform").submit(function (eventData, handler) {
var resultFromAction = ???
// I would like to get the object from the action returned
});
)
Or
function Save(
var resultFromAction = $("#myform").submit();
// I would like to get the object from the action returned
)
Code action in controller:
public class MyControllerController: Controller {
[Authorize]
public ActionResult Save(FormObject formobj) {
// do something
var resultForClient = new {
phone: "098989878",
name: "john",
add: "My address"
};
return Json(resultForClient, JsonRequestBehavior.AllowGet);
}
}
Firstly you should place the <button> within the <form> and change its type to submit:
<form action="/Mycontroller/Save" id="myform" enctype="multipart/form-data" method="post">
First name:<br />
<input type="text" name="firstname" value="Mickey"><br />
Last name:<br />
<input type="text" name="lastname" value="Mouse"><br /><br />
<button class="btn btn-success" type="submit">Save</button>
</form>
You can then attach an event handler directly to the submit event of the form to send your AJAX request using jQuery's $.ajax() method:
$("#myform").submit(function(e) {
e.preventDefault(); // stop the standard form submission
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(data) {
console.log(data); // the object returned from your Action will be displayed here.
}
});
});

My ajax post will not stop running (C#,JQuery,Ajax)

My Ajax call works. It sends data to the database as expected.
However, after it completes this task, it will not call the success or fail function. It just keeps running. I set the timeout for the ajax call but it didn't work.
I have a form in my html page
<form class="form-horizontal" id="signupForm" role="form" method="post" name="signupForm" action="">
<div class="form-group">
<label class="col-xs-3 control-label" for="TextBoxUsername">Username:</label>
<div class="col-xs-9"><input type="text" placeholder="username" id="TextBoxUsername" class="form-control" /></div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label" for="TextBoxPassword">Password:</label>
<div class="col-xs-9"><input type="text" placeholder="password" id="TextBoxPassword" class="form-control" /></div>
</div>
<div class="form-group">
<label class="col-xs-offset-5 control-label" for="selectImage" style="font-weight:bold;font-size:15px;">Choose Your Avatar</label>
</div>
<div class="content">
// I used the Image-Picker jQuery plugin here to create a selection of images and show them as thumbnails
<select name="selectImage" class="image-picker" id="selectImage" form="signupForm">
<option class="grid-item" data-img-src="img1.png" value="img1.png">Image 1</option>
<option class="grid-item" data-img-src="img2.png" value="img2.png">Image 2</option>
<option class="grid-item" data-img-src="img3.png" value="img3.png">Image 3</option>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</form>
This is my jQuery:
// this is my main jQuery function
$(function () {
// this is my form submit function
$("form").submit(function (e) {
e.preventDefault(); // this stops the form from refreshing the page
create();
});
});
// this function creates an object to be added to the database
function create() {
user = new Object();
user.Username = $("#TextBoxUsername").val();
user.Password = $("#TextBoxPassword").val();
// here I am getting the value of the selected item from <select> div
selectedImage = document.signupForm.selectImage.options[document.signupForm.selectImage.selectedIndex].value;
// this is just to convert the image to base 64 string.
var img = new Image();
img.src = selectedImage;
// draw canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0,0);
var imageURL = canvas.toDataURL();
user.Image = imageURL;
// end base 64 string conversion
$.ajax({
type: "Post",
url: "api/signup", // this url goes to a controller, it works perfectly
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
timeout: 3000, // does not do anything!
success: function () {
// this function is not being called!
$("#lblstatus").text("User was created!");
},
error: function (jqXHR, textStatus, errorThrown) {
// this function is not being called either!
errorRoutine(jqXHR);
}
});
}; // end create function
Like I said, the database is receiving the data just fine. But for some reason, this ajax call will not stop running. If I manually stop the application from the debugger, I can check the database and everything worked. I just need this ajax call to complete.
Try changing the type to button and set an id to it <button type="button" class="btn btn-default" id="submitbtn" >Sign in</button> And handle it by jquery click function $("#submitbtn").click(function () {
create();
});
by that, the page will not refresh even if you don't have the e.preventDefault();
since your using an ajax, the form is not needed anyway. So it can work even if you don't have a form tag
I found the tiny typo culprit.
it was inside the success function. I didn't add the "#" in front of "("lblstatus"). It should have been ("#lblstatus").
silly silly mistake.
Thanks for all the suggestions. It turned out to be a typo afterall.

ASP.Net MVC AJAX upload file to controller is being submitted twice

I have an ASP.Net MVC application. I need to send a file to Controller with ajax. but I have twice request.
#using (Ajax.BeginForm("Create", "MyController", new { area = "" },
new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "onBegin",
OnSuccess = "onSuccess(data)"
}, new { enctype = "multipart/form-data", id = "myform" }))
{
<section class="col col-md-12">
#Html.DisplayFor(model => model.Title)
<label class="input">
#Html.TextBoxFor(model => model.Title)
</label>
</section>
<section class="col-md-6">
<label class="label text-left">
My File
</label>
<label for="file" class="input input-file">
<div class="button">
<input name="files" type="file" id="file" onchange=" this.parentNode.nextSibling.value = this.value ">choose...
</div>
<input type="text" readonly="" class="text-right">
</label>
</section>
<button type="submit" class="btn btn-primary">
Submit
</button>
}
Controller Action, When posting my data using AJAX, here's twice request in my Action.
[HttpPost]
public ActionResult Create(HttpPostedFileBase files, CreateViewModel model)
{
// The Request comes here twice.
}
and my references in page,
<script src="/Scripts/jquery.min.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="/Scripts/bootstrap/bootstrap.min.js"></script>
<script src="/Scripts/jquery.form.js"></script>
$(function () {
$('#myform').ajaxForm({
beforeSubmit: ShowRequest,
success: SubmitSuccesful,
error: AjaxError
});
});
function ShowRequest(formData, jqForm, options) {
var queryString = $.param(formData);
alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
return true;
}
function AjaxError() {
alert("An AJAX error occured.");
}
function SubmitSuccesful(responseText, statusText) {
alert("SuccesMethod:\n\n" + responseText);
}
what should I do?
The problem is that you are using ASP.NET MVC AjaxForm as well jQuery ajaxForm plugin. When you press submit button, the request is sent by MVC as well jQuery.

Categories