I want to use html to get WebApi ReturnValue. (type:Get、datatype:Jsonp)
Now when I direct execution WebApi, it can get ReturnValue "2" (indicate execution Success).
But when via by html + Jquery + ajax , it always show error function information.
How an I resolve this problem, thanks.
------------- code -------------
API Model:
public class LoginModel
{
public int Userno { get; set; }
public List<Second> LoginSecond { get; set; }
}
public class Second
{
public string testinfo01 { get; set; }
public string testinfo02 { get; set; }
public List<Third> Third { get; set; }
}
public class Third
{
public string finValue { get; set; }
}
API Controller:
[HttpGet]
public string Get(string id, string id1) //id=Account,id1=password
{
string conn = ConfigurationManager.ConnectionStrings["testconn"].ConnectionString;
string Dictionary = Login.Login(id, id1).ToString();
return Dictionary;
}
Html:
<div class="form" id="form">
<form class="login-form" method="get">
<input type="text" id="inpAcc" placeholder="Acc"/>
<input type="password" id="inpPwd" placeholder="pwd"/>
<input id="loginbtn" type="button" value="login"></input>
<input id="data" type="label" />
</form>
</div>
jquery + ajax:
<script type="text/javascript" >
$(document).ready(function() {
$(document).on('click', '#loginbtn',function(){
var username = $("input#inpAcc").val();
var password = $("input#inpPwd").val();
alert(username);
var APIurl = "localhost:10733/Api/Login/";
$.ajax({
type: "get",
dataType: 'jsonp',
username:username,
password:password,
url: APIurl +"/"+username+"/"+password,
async: false,
headers: { "cache-control": "no-cache" },
contentType: 'application/json; charset=utf-8',
data :function (data)
{
var returnvalue = data[0].request();
console.log(data.stat);
console.log(data.status);
console.log(data.message);
console.log(data.html);
alert(returnvalue);
},
error: function(request, status, error) {
console.log(request.stat);
console.log(request.status);
console.log(request.message);
console.log(request.html);
alert(request.responseText);
},
success: function(data) {
console.log(data.stat);
console.log(data.status);
console.log(data.message);
console.log(data.html);
alert(data);
}
});
});
});
</script>
Please check your source. Remove the route configuration as below source included route config inline.
[RoutePrefix("api/Login")]
public class LoginController : ApiController
{
[HttpGet]
[Route("Get/{id}/{id1?}")]
public string Get(string id, string id1 = null) //id=Account,id1=password
{
return "Working";
}
}
to call above api your url should be like
http://localhost:11299/api/login/Get/id/id1/
In the above id1 is optional
Related
I am new to mvc and I am tring to use ajax to get and post data. Get is working fine but when I use post using the same ajax code while change it to post give me always error 400. I tried with many type of data sent and the action in the controller is empty to eleminate that the error occour there although i new 400 error is a bad request but I couldn't figure it out.
The code is as follow
async function SaveTheDay(url, data) {
if (data != null) {
$.ajax({
url: url,
type: 'POST',
dataType: "json",
data: data,
success: function (response) {
if (response) {
console.log("Ok");
} else {
console.log("not valid ");
}
},
error: function (req, status, error) {
console.log("error "+status+" "+error);
}
})//not null
}
}//SaveTheDay
the controller action is :
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SaveDay(InfoDay day)
{
return View("DayTrial");
}
and I call the function when the save button cliked as:
//define the object
var infoDay =
{
userId :userId,
date: TheDate.value ,
items :items ,
itemsAmount : itemsAmount,
itemsMealTime :itemsMealTime,
dailyConsumedkCal: dailyConsumedkCal,
dayTotal :"",
bloodData :"",
bloodSugarData :"",
sleepData :"",
indexData :"",
dayCost :0
}
SaveTheDay("/Days/SaveDay", infoDay);
here is the InfoDay class
public class InfoDay
{
public int userId { get;
set; }
public string date { get; set;
}
public string? items { get;
set; }
public string? itemsAmount {
get; set; }
public string? itemsMealTime {
get; set; }
public int? dailyConsumedkCal
{ get; set; }
public string? dayTotal {
get; set; }
public string? bloodData {
get; set; }
public string? bloodSugarData
{ get; set; }
public string? sleepData {
get; set; }
public string? indexData {
get; set; }
public int? dayCost { get;
set; } = 0;
}
The ValidateAntiForgeryToken attribute prevents 'Cross-site request forgery' attacks in your MVC application.
See https://learn.microsoft.com/..../security/anti-request-forgery?view=aspnetcore
Do not remove it.
To avoid the 400 error, you must pass the token with your POST request.
async function SaveTheDay(url, data) {
if (data != null) {
$.ajax({
url: url,
type: 'POST',
dataType: "json",
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader('RequestVerificationToken',
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
if (response) {
console.log("Ok");
} else {
console.log("not valid ");
}
},
error: function (req, status, error) {
console.log("error "+status+" "+error);
}
})//not null
}
}//SaveTheDay
Of course the hidden field with the token has to be present in the view.
The HTML Helper Html.AntiForgeryToken includes the token.
#Html.AntiForgeryToken()
If you use a form tag helper, the token is also included.
See https://learn.microsoft.com...?view=aspnetcore-6.0#the-form-tag-helper
I send model with ajax on server with post request.
I have next model and a controller that has a method of fasting.
public class TestDto: BaseDto
{
[Required]
public ProductGalleryDto GalleryProduct { get; set; }
public int? RetailPriceEur { get; set; }
[Required]
public int? AmountSpc { get; set; }
public bool? PrizeSent { get; set; }
public string Comment { get; set; }
public DateTime? StartDate { get; set; }
[Required]
public DateTime? ExpirationDate { get; set; }
public bool IsParticipant { get; internal set; }
}
public override IActionResult Post([FromBody] TestDto item)
{
if (!IsAdmin)
return BadRequest(ApiErrorCodes.InsufficientPriveleges);
if (!ModelState.IsValid)
return BadRequest(ApiErrorCodes.RequiredFieldsMissing, ModelState.Keys.FirstOrDefault());
}
JS:
var object = JSON.stringify({
createddate: startdate,
retailpriceeur: price,
amountspc: spobicoinprice,
prizesent: false,
expirationdate: expirationdate,
comment: comment,
productgalleryid: productgalleryDto
});
$.ajax({
headers: { "Authorization": "Bearer " + localStorage.getItem('authToken') },
url: "/api/testapi/",
method: "post",
data: object,
contentType: "application/json; charset=utf-8",
success: function (result) {
}
});
Fields in js are also present in the model
Actual: model is not valid.
How me fix that? Please, help
You Shroud send an object not JSON string in ajax request as this example :
var person = new Object();
person.name = "name";
person.surname = "surname";
$.ajax({
url: 'http://localhost:3413/api/person',
type: 'POST',
data: person,
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
From an ajax call I get some data which I want to pass to another window in a button click. I receive the data successfully but when that data is passed, in controller methods parameter is receiving the value as null.
<script>
$(document).ready(function () {
$('#btnSalesInAmount').click(function () {
var data = {
toDate: $('#todatepicker').val(),
fromDate: $('#fromdatepicker').val(),
customerId: $('#CustomerId').val()
};
$.ajax({
type: 'Get',
url: '/Reports/SalesInAmount' + '?toDate=' + data.toDate + '&fromDate=' + data.fromDate + '&customerId=' + data.customerId,
data: data,
success: function (data) {
window.open("/Reports/SalesInAmountView" + '?salesInAmount=' + data, 'SalesInAmountViewWindow', "features");// the data is not received by controllers method
}
});
});
});
</script>
in controller
public ActionResult SalesInAmountView(SalesInAmount salesInAmount) // parameter value is null
{
return View();
}
the model
public class SalesInAmount
{
public DateTime SalesDt { get; set; }
public int SalesSl { get; set; }
public int CustomerSupplyId { get; set; }
public string CustomerSupplyNm { get; set; }
public double TotalSalesByCustomer { get; set; }
public double TotalDiscount { get; set; }
public double TotalVat { get; set; }
public double TotalSales { get; set; }
public List<SalesInAmount> List { get; set; }
}
Try this ,
Simplify Your Data Set ,
var Param1= $('#ID').val();
var Data = JSON.stringify({ Data1 : Param1, . . });
Ajax
$.ajax({
url: '#Url.Action("Action_Name", "Controller_Name")',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
data: Data,
cache: false,
success: function (data) {
});
}, error: function (request, status, error) {
}
});
}
Controller
public JsonResult Action_Name(string Data1 , . . )
{
return Json(Some_Json);
}
Note : this Controller Return Json Result , It depends on requirement .
You need to stringify the javascript object before pass as the parameter , JSON.stringify() is the function in javascript
<script>
$(document).ready(function () {
$('#btnSalesInAmount').click(function () {
var data = {
toDate: $('#todatepicker').val(),
fromDate: $('#fromdatepicker').val(),
customerId: $('#CustomerId').val()
};
$.ajax({
type: 'Post',
url: '/Reports/SalesInAmount',
data: JSON.stringify(data),
success: function (data) {
window.open("/Reports/SalesInAmountView" + '?salesInAmount=' + data, 'SalesInAmountViewWindow', "features");// the data is not received by controllers method
}
});
});
});
Make sure you have given same name of variable as you modal class SalesInAmount.
[HttpPost]
public ActionResult SalesInAmountView(SalesInAmount salesInAmount) // parameter value is null
{
return View();
}
I get this result from creating JSON in my view
header:{"ScheduledVisit":"08/02/2017 12:00 AM","Company":"fdsa","ContactPerson":"asfd","Phone":"asdf","Purpose":"fasd","Detail":"asdf"}
My model looks like this:
public class ScheduleVisit
{
[Required(ErrorMessage = "* Required")]
public DateTime ScheduledVisit { get; set; }
public string Company { get; set; }
public string ContactPerson { get; set; }
public string Phone { get; set; }
public string Purpose { get; set; }
public string Detail { get; set; }
}
I pass my data like so:
document.getElementById("btn_submit_schedule").addEventListener("click", function (event) {
event.preventDefault();
if ($("#scheduledVisit").val().length === 0) {
$("#scheduledVisit").focus();
}
var obj = {};
obj.ScheduledVisit = document.getElementById("scheduledVisit").value;
obj.Company = document.getElementById("company").value;
obj.ContactPerson = document.getElementById("contactPerson").value;
obj.Phone = document.getElementById("phone").value;
obj.Purpose = document.getElementById("purpose").value;
obj.Detail = document.getElementById("detail").value;
console.log(obj);
addSchedule(obj);
});
function addSchedule(data) {
$.ajax({
type: "POST",
url: "#Url.Action("ScheduleVisit", "ScheduleVisit")",
data: {header: JSON.stringify(data)},
success: function(result) {
alert(result);
},
error: function(error) {
alert(error);
}
});
}
and my controller looks like this:
[HttpPost]
public JsonResult ScheduleVisit(ScheduleVisit header)
{
return Json(false);
}
When I run in debug mode and check if my controller accepts anything, I get null on the "header" parameter. Please show me where I am getting it wrong.
Just replaced data: {header: JSON.stringify(data)} with data: data with current solution.
This very complex and manual way you'll can use simple way as following
Assign name field to every element as same like id now
<input type="text" name="Company" value="" />
Use serializeArray
data: $("form").serializeArray(),
Hope this will help.
The problem is that "data: {header: JSON.stringify(data)}" is not the same object as you expect on the controller.
This should work.
$.ajax({
type: "POST",
url: "#Url.Action("ScheduleVisit", "ScheduleVisit")",
data: data,
...
The controller expects an object like:
{
"ScheduledVisit":"08/02/2017 12:00 AM",
"Company":"fdsa",
"ContactPerson":"asfd",
"Phone":"asdf",
"Purpose":"fasd",
"Detail":"asdf"
}
I have an AJAX-enabled WCF service with the following signature:
[OperationContract]
[WebGet]
public JQGridContract GetJQGrid(int entityIndex)
And the following data contract:
[DataContract]
public class JQGridContract
{
[DataContract]
public class Row
{
[DataMember]
public int id { get; set; }
[DataMember]
public List<string> cell { get; set; }
public Row()
{
cell = new List<string>();
}
}
[DataMember]
public int page { get; set; }
[DataMember]
public int total { get; set; }
[DataMember]
public int records { get; set; }
[DataMember]
public List<Row> rows { get; set; }
public JQGridContract()
{
rows = new List<Row>();
}
}
Basically I need to change the postData of the client-side jqGrid to send 'entityIndex' to this service.
I've read how its supposed to function and from what I can tell this should work:
function loadGrid() {
$("#jqGrid").jqGrid({
postData: { entityIndex : function () { // modify the data posted to AJAX call here
return 6;
})
},
gridComplete: function () {
$("#jqGrid").setGridParam({ datatype: 'local' });
},
datatype: function (pdata) {
getData(pdata);
},
And here is the getData() function:
function getData(pdata) {
var params = new Object();
alert(pdata.entityIndex()); // this displays '6', correctly
params.entityIndex = pdata.entityIndex();
$.ajax(
{
type: "GET",
contentType: "application/json; charset=utf-8",
url: "AJAXService.svc/GetJQGrid",
data: JSON.stringify(params),
dataType: "json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#jqGrid")[0];
thegrid.addJSONData(data.d);
}
},
error: function (data, textStatus) {
alert('An error has occured retrieving data!');
}
});
Ive confirmed the following in Firebug:
1) The json params are correct : {"entityIndex":6}
2) The AJAX service returns JSON data to the grid, its just the wrong data
And here is the wierd part:
I logged the 'entityIndex' thats actually working inside the WCF operation -- and its ALWAYS coming up as 0?
Thanks.
I will not criticize the style of your program. I could write too many things about this. :-)
You current main problem could be solved with the usage JSON.stringify(pdata.entityIndex()) instead of JSON.stringify(params) or with the usage of another BodyStyle of the WFC method (see here for details)
I got it working, it is close to what Oleg said, just that you do not need to do JSON.stringify.
If you have WebMessageBodyStyle.WrappedRequest, this works:
data: { entityIndex: pdata.entityIndex() },
OR if you have no BodyStyle, this works:
data: { "entityIndex": pdata.entityIndex() },