I was trying to figure out how I get the body of the JSON object, that I was sending with the listed AJAX POST request.
While debugging the UploadJSON method gets called but is having a jsoninput with null content.
//ASP.NET Core
[HttpPost]
public IActionResult UploadJSON([FromBody] IFormCollection jsoninput)
{
var inputBody = jsoninput;
// Writing JSON object content into a file....
return RedirectToAction("Index");
}
//javascript
function uploadJSON(plistArrayForJSON) {
var sendobj = JSON.stringify({ plistArrayForJSON });
$.ajax({
url: 'https://localhost:5001/home/uploadjson',
type: 'POST',
data: sendobj,
contentType: "application/json",
});
}
The JSON you send is not deserializable as IFormCollection.
//ASP.NET Core
[HttpPost]
public IActionResult UploadJSON([FromBody] IList<PlayList> jsoninput)
{
var inputBody = jsoninput;
// Writing JSON object content into a file....
return RedirectToAction("Index");
}
Related
I am new to ASP and I am trying to take a string in my JS code and post it to my controller so that I can use it to query my database.
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (response) {
alert(userCounty);
},
error: function (response) {
alert("failed");
}
});
}
Controller
[HttpPost]
public ActionResult Index (string userCounty)
{
var query = //use linq to query database
return View(query);
}
I only ever get the "success" alert when I use a JsonResult function in my Controller but I need it to eventually return a LINQ query to the View(); function and that hasn't worked when using a JsonResult function. Any ideas would be helpful. I don't necessarily have to use ajax if there is a better way. I just need a way to pass the string stored in userCounty to my controller.
Please change your controller method like this
[HttpPost]
public ActionResult Index([FromBody]string userCounty)
{
var query = //use linq to query database
return View(query);
}
For viewing the page, you'll need
[HttpGet]
public ActionResult Index()
{
return View();
}
I have been trying to send a list model to controller using ajax but it seems it is not working at all
Model
public string MyModel {
public string myfieldName {get;set;}
}
controller
public JsonResult Create(List<myModel> list)
{
return Json("Success");
}
post request
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC' }, { myfieldName: 'DEF' }];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: JSON.stringify({ list }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
so when I send this through, I check the browser and I can see that the request payload is sent with json object list
However when I go to controller the list is not binding it at all, so I check the http.context to check the request payload there and it all empty.
on the other hand when I change the controller like below
sending request with only model
public JsonResult Create(myModel data)
{
return Json("Success");
}
and change the js with below
$("body").on("click", "#btnSave", function () {
var data ={};
data.myfieldName= "test";
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: data,
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
the only difference here is that I don't send as json, so my question what is the is the difference between sending model vs a list of model using ajax
and what can I change to get the controller to bind the data or accept a list of model data
noting i'm using .Net core 2.0
Thank you
I usually use this method to send my Model as a List to my Controller method. I will try to show you regarding your scenario, how you can do this:
AJAX:
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC'}, { myfieldName: 'DEF'}];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "#Url.Action("Create","Project")",
data:{"json": JSON.stringify(list)},
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
And you can receive your Model like this in your Create method:
Make sure to import the System.Web.Script.Serialization namespace:
using System.Web.Script.Serialization
[HttpPost]
public JsonResult Create(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
List<string> myfieldName=new List<string>();
//Access your array now
foreach (var item in jsondata)
{
myfieldName.Add(item["myfieldName"]);
}
//Do something with the list here
return Json("Success");
}
Hope this helps you out.
Another method would be to utilize unobtrusive AJAX. All you would need is to install Microsoft jQuery unobtrusive AJAX from your Nuget Package Manager.
Then, in your view, call the following:
#{using (Ajax.BeginForm("Create", "ControllerName", null, new AjaxOptions()
{
HttpMethod = "POST",
// ...
}
}))
{
// Html code goes here
}
And also make sure that you include this at the bottom of your view:
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Then, you can have a normal ActionResult setup (instead of JsonResult) for your controller and accept an argument of List list.
I try to send antiforgerytoken and yeniTest is filled by some data ( it is not null ) to controller via below code at html page.
var token = document.querySelector('input[name="__RequestVerificationToken"]').value;
$.ajax({
url: '#Url.Action("/TestCevabı")',
type: 'post',
data: { __RequestVerificationToken: token, yeniTest: JSON.stringify(yeniTest)},
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
traditional: true
});
Controller method is like below
[HttpPost]
[ValidateAntiForgeryToken]
public bool TestCevabı(Test yeniTest)
{
///
}
I pass ValidateAntiForgeryToken at controller method.But yeniTest at TestCevabı method is null.
I changed the controller method as below.
[HttpPost]
[ValidateAntiForgeryToken]
public bool TestCevabı(string yeniTest)
{
///
}
and add following code to TestCevabıService
Test çözülenTest = new Test();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(testJsonFormat)))
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(çözülenTest.GetType());
çözülenTest = ser.ReadObject(ms) as Test;
ms.Close();
}
Now antforgerytoken pass and Test object filled
I have this javascript code:
var formData = new FormData($('#formSlip').get(0));
formData.append('myList', JSON.stringify(tests));
Where tests is a list of objects. I'm sending an ajax post request to my controller and within that request I'm sending a file and a list of objects.
$.ajax({
url: url,
type: 'post',
data: formData,
processData: false,
contentType: false,
cache: false,
success://some code
})
I've took a look into my Request Payload using DevTools in Chrome, and it looks like this:
Content-Disposition: form-data; name="firstPdf"; filename="blank.pdf"
Content-Type: application/pdf
Content-Disposition: form-data; name="myList"
[{"key":"Section1","listTitles":["aaaa","aa","aa","a"]},
{"key":"Section2","listTitles":["bb","b","bb","b"]}]
I'm retrieving the file okay in my controller action, but for some reason the list is always empty, this is my controller action:
[HttpPost]
public ActionResult LS10(HttpPostedFileBase firstPdf, List<PdfPieceVM> myList)
{
var t = firstPdf.InputStream;
byte[] pdfByte = new byte[firstPdf.ContentLength];
return File(pdfByte, "application/pdf", firstPdf.FileName);
}
I've created a ViewModel just to get that list:
public class PdfPieceVM
{
public string key { get; set; }
public List<string> listTitles { get; set; }
}
When I debug my code the myList parameter is always empty, but I'm receiving the file, what do I need to do to correct this?
Reading #Alex Menconi referenced post, I changed the controller action to retrieve a string and then deserialize it to the type that I wanted:
[HttpPost]
public ActionResult LS10(HttpPostedFileBase firstPdf, string myList)
{
List<PdfPieceVM> pdfPieces = new
JavaScriptSerializer().Deserialize<List<PdfPieceVM>>(myList);
}
I have two forms, consider Form1 and Form2, both are MVC forms only. These forms using two different view models as shown below :
public class Form1ViewModel
{
//some public properties
public string QueryString { get; set; }
}
public class Form2ViewModel
{
//some public properties
public string PreviousQueryString { get; set; }
}
In the controller Post Action I'm writing like this :
[HttpPost]
public ActionResult ProcessForm1(Form1ViewModel form1Obj)
{
//some logic goes here
//I'm preparing Querystring from form1 data and appending to Form2 model like
Form2ViewModel form2Obj=new Form2ViewModel();
form2Obj.PreviousQueryString = form1Obj.QueryString;
return View("Form2",form2Obj) ;
}
And in Form1, I'm submitting through Jquery Ajax as
frm.submit(function(ev) {
var formData = frm.serialize();
$.ajax({
type: "POST",
url: 'ControllerName/ProcessForm1',
data: formData,
success: function(response) {
//Here i need to read the PreviousQueryString and need to push to window.history.pushState()
}
error: function() {}
});
});
In the Ajax success, I need to read the PreviousQueryString from the response.
I knew how to do it client side(using pure JS) but it's my requirement.
How can I do it?
Try this
[HttpPost]
public string ProcessForm1(Form1ViewModel form1Obj)
{
JavaScriptSerializer js = new JavaScriptSerializer();
Form2ViewModel form2Obj=new Form2ViewModel();
form2Obj.PreviousQueryString = form1Obj.QueryString;
return js.Serialize(form2Obj);
}
success: function(response) {
var objResponse = $.parseJSON(response);
if (objResponse.PreviousQueryString != "") {
alert(objResponse.PreviousQueryString);
}
}