I have a asp.net core 3.0 application with WebPages and I try to send a JSON via ajax to my handler. But the parameter is always null or just filled with the default values. I tried to if the JSON string from the post is parseable and it works when I parse manually.
This is my controller:
public void OnPost([FromBody]FilterModel filter)
{
Console.Write(filter);
}
This is the model class:
public class FilterModel
{
public DateTime TimeRangeFrom { get; set; }
public DateTime TimeRangeTo { get; set; }
public int CustomerId { get; set; }
}
The ajax request:
$.ajax({
url: "/CustomerOverview/Test",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
CustomerId: customerId,
TimeRangeFrom: picker.startDate,
TimeRangeTo: picker.endDate
}),
beforeSend: function(xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function(response) {
button.hide();
},
failure: function(response) {
alert(response);
}
});
And the JSON as logged in Chrome Dev Tools:
{CustomerId: "1", TimeRangeFrom: "2019-08-26T22:00:00.000Z", TimeRangeTo: "2019-09-25T21:59:59.999Z"}
Do I have to setup a mapping or something?
FromBody attribute will parse the model the default way which in most cases are sent by the content type application/json from the request body.So if you fill a form and pass the form data to the controller action,you need to convert the JavaScript object into a string with JSON.stringify().
FromForm attribute is for incoming data from a submitted form sent by the content type application/x-www-url-formencoded.
Reference:https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.0#sources
Turns out that it can't convert an "1" to an int. I had to convert the value for customerId to a int first so that I have this JSON:
{
"CustomerId": 1,
"TimeRangeFrom": "2019-08-26T22:00:00.000Z",
"TimeRangeTo": "2019-09-25T21:59:59.999Z"
}
Related
I am using a button OnClick event to try and save a record to a database using AJAX in ASP.NET Core. The function is not returning an error, however, the data is not being saved. I am just trying to test with hard coded data first. A record with AdapollingProjectProcessStatusId = 1 exists in the database.
function SendHtmlEditorValueToController(data) {
$.ajax({
type: 'POST',
url: '#Url.Action("AJAXPost", "LiveAdapollingProjectProcessStatus")',
contentType: "application/json",
data: JSON.stringify({ "id": 1, "status": 'test'}),
dataType: 'json',
success: () => {
console.log("value is sent");
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
}
LiveAdapollingProjectProcessStatusController:
[HttpPost]
public JsonResult AJAXPost(int id, string status)
{
LiveAdapollingProjectProcessStatus processstatus = new LiveAdapollingProjectProcessStatus
{
AdapollingProjectProcessStatusId = id,
AdapollingProjectProcessStatus = status
};
//save it in database
return Json(processstatus);
}
LiveAdapollingProjectProcessStatus.cs:
namespace CPSPMO.Models.PMO
{
public partial class LiveAdapollingProjectProcessStatus
{
public int AdapollingProjectProcessStatusId { get; set; }
public string AdapollingProjectProcessStatus { get; set; }
}
}
Please let me know if you are able to help me with this AJAX Post.
Thanks
Not sure how do you store it to the database, but the way you pass parameter to backend by ajax should be like below:
function SendHtmlEditorValueToController(data) {
$.ajax({
type: 'POST',
url: '#Url.Action("AJAXPost", "LiveAdapollingProjectProcessStatus")',
//contentType: "application/json", //remove this...
data:{ "id": 1, "status": 'test'}, //modify here...
dataType: 'json',
success: () => {
console.log("value is sent");
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
}
After reviewing the comments regarding missing code for saving the data in the database, I modified the controller:
[HttpPost]
public JsonResult AJAXPost(int id, string status)
{
LiveAdapollingProjectProcessStatus processstatus = new LiveAdapollingProjectProcessStatus
{
AdapollingProjectProcessStatusId = id,
AdapollingProjectProcessStatus = status
};
//save it in database
var result = _context.LiveAdapollingProjectProcessStatuses.Update(processstatus);
_context.SaveChanges();
return Json(processstatus);
}
It is saving the data to the database now. Thanks for the help
I have a front end calling an axios request to a web api in ASP.NET Core and for some reason my model will not bind. I am sending email data to the web api and trying to bind it to an email and contact model. It just keeps showing the email object as null. My axios request seems to be working okay as it does send the payload but errors out in the API due to the email object being null.
JS
axios({
method: 'post',
url: window.location.origin + '/MainReview/SendEmail',
data: {
From: this.emailFrom,
To: this.emailToModel,
Cc: this.emailCcModel,
Bcc: this.emailBccModel,
Subject: this.emailSubject,
Body: this.emailBody,
},
headers: {
'Content-Type': 'multipart/form-data',
"RequestVerificationToken": document.forms[0].querySelector('input[name="__RequestVerificationToken"]').value,
}
}).then(response => {
}).catch(error => {
console.log(error.response.data.error);
});
Web API
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SendEmail([FromBody] Email email)
{
System.Diagnostics.Debug.WriteLine(email.From);
return Ok(new { Result = email.From });
}
Model:
public class Email
{
public string? From { get; set; }
public IEnumerable<Contact>? To { get; set; }
public IEnumerable<Contact>? Cc { get; set; }
public IEnumerable<Contact>? Bcc { get; set; }
public string? Subject { get; set; }
public string? Body { get; set; }
}
public class Contact
{
public string EmailAddress { get; set; }
}
Json data sent in payload:
{ "From":"emailfrom#example.com", "To":[ { "EMAIL_ADDRESS":"emailTo#example.com" }, { "EMAIL_ADDRESS":"emailCC#example.com" } ], "Cc":[ { "EMAIL_ADDRESS":"emailCC2#example.com" } ], "Bcc":[ ], "Subject":"Temporary Placeholder", "Body":"tessdf" }
I believe my issue is something with the IEnumerable. I will be honest I have stayed away from models but I figure I will start trying to use them more since its best practice. However, this is driving me nuts as I do not see why this would not work.
1.You use [FromBody] in backend and post json data in frontend, the Content-Type should be application/json.
headers: {
'Content-Type': 'application/json', //change here....
"RequestVerificationToken": document.forms[0].querySelector('input[name="__RequestVerificationToken"]').value,
}
2.The posted json data is not correct because the property in Contact model is named EmailAddress, but you post json with name EMAIL_ADDRESS.
data: { "From":"emailfrom#example.com", "To":[ { "EmailAddress":"emailTo#example.com" }, { "EmailAddress":"emailCC#example.com" } ], "Cc":[ { "EmailAddress":"emailCC2#example.com" } ], "Bcc":[ ], "Subject":"Temporary Placeholder", "Body":"tessdf" },
Ensure the structure matches methods parameter class.
Here, we've got an email parameter, which is an object {}. And it also has properties which are a list of objects [{}].
data: {
From: this.emailFrom,
To: [{ EmailAddress: this.emailToModel }],
Cc: [{ EmailAddress: this.emailCcModel }],
Bcc: [{ EmailAddress: this.emailBccModel }],
Subject: this.emailSubject,
Body: this.emailBody,
}
Note: If you were passing more than one parameter you need to specify the parameter name as well, with an extra set of {}.
data: {
email: {
From: this.emailFrom,
To: [{ EmailAddress: this.emailToModel }],
Cc: [{ EmailAddress: this.emailCcModel }],
Bcc: [{ EmailAddress: this.emailBccModel }],
Subject: this.emailSubject,
Body: this.emailBody,
},
parameter2:"XXXXXXXXX"
}
ASP.NET Core 5.0 Razor Pages.
When posting the array, the model is not binding - value is showing empty array.
This is a JSON array posted using Ajax -
[
{ "Order":1, "FileName":"bbed5ecf-4133-4681-b0f3-c11366ad3186.jpg" },
{ "Order":2, "FileName":"737e60dc-0631-493d-947d-2f5948d7818c.jpg" },
{ "Order":3, "FileName":"6c76f9d1-44bd-4b80-926e-2ce4307eb30b.jpg"}
]
function UpdateImageOrder() {
$.ajax({
type: "POST",
url: "/property/imagesorter",
dataType: "json",
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(newOrderDictionary),
success: function (response) {
}
});
}
RazorPage action Method
public async Task OnPostAsync(ImageOrder[] data)
{
}
public class ImageOrder
{
public int Order { get; set; }
public string FileName { get; set; }
}
The data parameter of the POST should be the object value, not a stringified version of it. Try changing to:
...
data: newOrderDictionary,
...
Assuming newOrderDictionary is an array.
Considering using post to pass data, you need to add contentType:"application/json" in ajax.
$.ajax({
type: "POST",
url: "/?handler",
dataType: "json",
contentType:"application/json",
//...
});
In addition, add [FromBody] in the bakend.
public async Task OnPostAsync([FromBody]ImageOrder[] data)
{
}
Then, it can get the data.
Turns out that this works :
public async Task OnPostAsync(ImageOrder[] order)
{
}
function UpdateImageOrder() {
$.ajax({
type: "POST",
url: "/property/imagesorter",
dataType: "json",
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
data: {
order: newOrderDictionary
},
success: function (response) {
}
});
}
I am currently attempting to do something that should be fairly straight forward, but to be honest is pretty far from it at the moment and its driving me a bit mad.
I've been consuming Get actions in my WebApi, however I'm trying to create Post actions in order to keep my mvc controllers clean however I can't for the life of me figure out why my get actions work as expected but my post action results in a 404
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using TamWeb.Models.api;
namespace TamWeb.Controllers.api
{
[Authorize]
[Route("api/[controller]")]
public class AdminController : Controller
{
[HttpPost]
public bool UpdateDetails([FromBody]DetailsViewModel model)
{
return false;
}
}
}
using System;
namespace TamWeb.Models.api
{
public class DetailsViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
The api controller is as simple as it gets and as per several other api questions instead of using string parameters I've created a model object and to follow other answers and what little out of date documentation I can find I consume the api as follows:
$(function() {
var firstname = $('#firstName').val();
var lastname = $('#lastName').val();
$.ajax({
url: "api/admin/UpdateDetails",
type: "POST",
data: JSON.stringify([firstname, lastname]),
success: function(data) {
console.log(data);
},
error: function() { console.log("error") }
});
});
As far as I can tell everything "should" work, however fiddler keeps telling me the url doesn't exist so now I'm at a loss as to whats wrong.
hopefully my answer can help you to deal with your question.
1.first issue you have to use "ApiController" instead "Controller"
2. [Authorize] <-- you have to get token key and then using it to get data from webapi
as following code, I will share you me simple code without Authorize,I wish it can solve your problems
client code
$("#read1").click(function () {
$.support.cors = true;
$.ajax({
crossDomain: true,
url: 'http://localhost:43520/api/Banners/',
datatype: "json",
contenttype: "application/json; charset=utf-8",
data: { id: 123 },
type: 'post',
error: function (xhr, status, errorThrow) {
alert(xhr.status);
},
success: function (data) {
alert(JSON.stringify(data));
}
});
});
server code
// GET: api/Banners/5
[ResponseType(typeof(Banners))]
public IHttpActionResult GetBanners(int id)
{
Banners banners = db.Banners.Find(id);
if (banners == null)
{
return NotFound();
}
return Ok(banners);
}
I have the json object like below
Extension = {
"BookMarks":
[{"Name":"User1","Number":"101"},
{"Name":"User2","Number":"102"},
{"Name":"User3","Number":"103"}]}
I want to send this json string to my controller Action method and Deserialize the data
I want to pass the data to the partialview
public ActionResult ExtensionsDialog(var data)
{
return PartialView(data);
}
Any help
Thanks in advance..
In your View:
function SendData(){
var dataToSend = JSON.stringify(data);
$.ajax({
type: "POST",
url: '#Url.Action("YourAction", "YourController")',
dataType: "json",
data: dataToSend,
contentType: "application/json; charset=utf-8",
});
}
$("#Updatebtn").click(function () {
sendData();
});
In you Model:
public class YourModel
{
public String Name { get; set; }
public int Number { get; set; }
}
In your Controller:
[HttpPost]
public ActionResult YourAction()
{
var resolveRequest = HttpContext.Request;
List<YourModel> model = new List<YourModel>();
resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
if (jsonString != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
model = (List<YourModel>)serializer.Deserialize(jsonString, typeof(List<YourModel>);
}
//Your operations..
}
Hope this helps.
I don't think you have to read the input stream yourself. If you provide a model the binder should do it for you.
In your code behind:
public class StatusInfo
{
public int ItemId { get; set; }
public int StatusId { get; set; }
}
[HttpPost]
public ActionResult EditStatus(StatusInfo info)
{
DoSomethingInteresting(info.ItemId, info.StatusId);
return new EmptyResult();
}
And just use the jQuery ajax function like so:
function changeStatus(itemId, statusId) {
var postData = { "ItemId": itemId, "StatusId": statusId };
$.ajax({
url: "/Item/EditStatus",
type: "POST",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, status) {
console.log("success updating status.");
},
error: function () {
console.log("error updating status.");
}
});
}
You can call the action and pass values like this. Just substitute your data with the data I have in the data section.
$.ajax({
url: '/Schedule/Schedule/Create',
type: 'POST',
cache: false,
datatype: JSON,
data: {
scheduleName: ScheduleName,
description: Desc,
Hol_Type: JSON.stringify(holidaytype),
Start_Date: start_date,
End_Date: end_date,
Start_Time: StartTime,
End_Time: EndTime,
days: JSON.stringify(days),
rec_type:1
},
success: function (data, status) {}});
You can pass your data via an ajax call like this :
$.ajax({
url : "#Url.Action("YourMethod", "YourController")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({Extension: data})
}).done(function (result) {
//Check if it's OK
}).fail(function (result) {
//Check if it is not OK
}).always(function() {
//Some code executed whatever success or fail
})
.done, .fail and .always are not compulsory, it's just better in my opinion.
Then use it in your Controller as you've done.
It should be OK.
Your script should be like:
Extension = {"BookMarks":[{"Name":"User1","Number":"101"},{"Name":"User2","Number":"102"},{"Name":"User3","Number":"103"}]}
$.ajax({
url : "#Url.Action("ExtensionsDialog", "Controller")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : {"data" : Extension }
});
Action method is same.
public ActionResult ExtensionsDialog(var data)
{
return PartialView(data);
}