Why this ajax post request does not work in mvc app - asp.net-mvc

i have js file with ajax request
this is part of its text
$.ajax({
url: '/Points/Addpoint', // также '#Url.Action("Addpoint", "PointsController")'
type: "POST",
dataType: "json",
data: JSON.stringify({ firstx: ev._x, firsty: ev._y, secondx: ev._x, secondy: ev._y }),
success: function () {
alert();
}
});
i also have mvc controller with this method which should be called in ajax
[HttpPost]
public void Addpoint(JSON po)
{
var pointslist = this.Getpoints();
var obj = po;
pointslist.Add(new Point());
}
But somehow this doesnt work. idk why?it gives me 500 error and message
There are no parameterless constructors defined for this object.
what should i do to solve this problem and send this json obj?

Change the JSON to class and change your post
public class YourClass
{
public string firstx { get; set; }
public string firsty { get; set; }
public string secondx { get; set; }
public string secondy { get; set; }
}
[HttpPost]
public void Addpoint([FromBody] YourClass po)
{
var pointslist = this.Getpoints();
var obj = po;
pointslist.Add(new Point());
}
$.ajax({
url: '/Points/Addpoint',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ firstx: ev._x, firsty: ev._y, secondx:ev._x,secondy: ev._y }),
success: function () {
}
});

Related

JSON object to ASP.NET MVC

I know there are multiple threads around this issue, but I still can't figure mine out. Can someone please help me figure out why my classObject always has null value? I feel like I've tried everything by now.
My class:
public class ClassAB
{
[Required]
[MaxLength(100)]
[DataType(DataType.Text)]
public string A{ get; set; }
[Required]
[MaxLength(100)]
[DataType(DataType.MultilineText)]
public string B{ get; set; }
}
My home controller:
[HttpPost]
public ActionResult MyMethod(ClassAB classObject)
{}
and my Javacript call
let data = {
"A": "A",
"B": "B"
}
await fetch(`https://localhost:44359/Home/MyMethod/`, {
method: "POST",
body: JSON.stringify(data),
contentType:"application/json",
success: (result)=>{
console.log(result)
},
failure: (result) => {
alert(result)
}
});
Found the issue. My contentType should have been in header. Modifying request to
await fetch(`https://localhost:44359/Home/MyMethod/`, {
method: "POST",
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
},
success: (result)=>{
console.log(result)
},
failure: (result) => {
alert(result)
}
});
fixed the issue
Try this
var data = [{A: 'A',B:'B'}];
await fetch(`https://localhost:44359/Home/MyMethod/`, {
method: "POST",
body: JSON.stringify(data),
contentType:"application/json",
success: (result)=>{
console.log(result)
},
failure: (result) => {
alert(result)
}
});
[HttpPost]
public ActionResult MyMethod(List<ClassAB > classObject)
{}
WebAPI won't know to model bind an object like that. See https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1
Try using the [FromBody] attribute
[HttpPost]
public ActionResult MyMethod([FromBody] ClassAB classObject)
{}
When combining this with a proper javascript post this will work, see image.
Sample js
<script>
var xhr = new XMLHttpRequest();
var url = "https://localhost:5001/api/default/MyMethod";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({ "A": "A", "B": "B" });
xhr.send(data);
</script>

How to post json object with multiple values to the Controller from Ajax

I have this Ajax post working for a single value but I need it to work with multiple values. What am I missing?
I have already tried to make the public class 'Value' a List AND Guid[]. I have tried to adjust the method parameter to List AND Value[]. Not sure what else to try.
Class:
public class Value
{
public Guid TimeId { get; set; }
}
Method:
public IActionResult ApproveAllTimesheets([FromBody]Value information)
View JS:
function SubAll() {
var selectedValues = $('#timesheet').DataTable().column(0).checkboxes.selected().toArray();
var instructions = {};
for (var TimeId in selectedValues) {
instructions[TimeId] = { TimeId: selectedValues[TimeId] };
}
var inst = JSON.stringify(instructions);
$.ajax({
url: "/Admin/ApproveAllTimesheets",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: inst,
success: function (result) {
alert(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};
If I send through this object it works but I need to send through multiple values like my ajax post will do.
var instructions = { TimeId: "13246578-1234-7894-4562-456789123456" };
UPDATE #1
I found a structure that works for me by extending the class, now I just need to figure out how to create the correct object and array combination.
New Classes:
public class ValueContainer
{
public List<Value> MasterIds { get; set; }
}
public class Value
{
public Guid TimeId { get; set; }
}
Method:
public IActionResult ApproveAllTimesheets([FromBody]ValueContainer information)
Structure I need now (this works hard coded):
var jsonObject = {
"MasterIds": [{ TimeId: "13246578-1234-7894-4562-456789123450" }, { TimeId: "13246578-1234-7894-4562-456789123451" }, { TimeId: "13246578-1234-7894-4562-456789123452" }]
};
I'm still new to this stuff but what I see is that jsonObject is an object with a Key 'MasterIds' and the corresponding values are an array of objects with the key 'TimeId'...is this a correct evaluation?...and how to create it in code please?
You neec to create an array of objects and then set it in the container object :
var instructions = []; // an array
for (var i = 0; i < selectedValues.length; i++) {
instructions.push({ TimeId: selectedValues[i] };
}
var Value = {TimeId: instructions}; // creating object with property TimeId as array of guid
var inst = JSON.stringify(Value);
.......
....... your ajax code
and your class property should also be of type array:
public Guid[] TimeId { get; set; }

image browser imageBrowser_listUrl not working

i have tried to get the plugin Image-Browser to work, but i cant figure out, what im missing here.
im using this class:
public class GetImagesToJsonClass
{
public string image { get; set; }
public string thumb { get; set; }
public string folder { get; set; }
}
and this JsonResult
public JsonResult GetFiles()
{
List<GetImagesToJsonClass> GetFiles = new List<GetImagesToJsonClass>();
DirectoryInfo GetDIR = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/Content/Images/"));
foreach (FileInfo item in GetDIR.GetFiles())
{
GetImagesToJsonClass NewFile = new GetImagesToJsonClass();
NewFile.image = string.Format("/Content/Images/{0}", item.Name);
NewFile.thumb = string.Format("/Content/Images/{0}", item.Name);
NewFile.folder = "Test";
GetFiles.Add(NewFile);
}
string GetJson = JsonConvert.SerializeObject(GetFiles);
return Json(GetJson, JsonRequestBehavior.AllowGet);
}
using this on a "test" site
<script>
var myURL = '#Url.Action("GetFiles", "Sales")';
var Getfiles = $.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: myURL,
data: "",
datatype: "Json",
});
Getfiles.done(function () {
try {
var tempdata = (Getfiles.responseText);
var data = JSON.parse(tempdata);
document.write(data);
}
catch (e) {
alert("fejl:" + e);
}
});</script>
and the output is:
[{"image":"/Content/Images/testimage2.jpg","thumb":"/Content/Images/testimage2.jpg","folder":"Test"}]
and ofc this to activat it
CKEDITOR.replace('editor1', {
"extraPlugins": 'imagebrowser',
"imageBrowser_listUrl": "/Sales/Test"
});
And get an error
parsererror: invalid JSON file: "/Sales/Test/": Unexpected token <
and if i set the feed directly in i get a [object, object] error?
what am i doing wrong here?

how to pass knockoutjs view model into a mvc controller

I have the following function in a MVC controller
public class XyzController:Controller
{
public ActionResult Index(){...}
[HttpPost]
public bool Save(string jsondata)
{
//parse json data to insert into the database
}
}
I want to pass this view model into the Save function
var myObj = function (id) {
var self = this;
self.myId = id;
self.parameters = ko.observableArray();
}
var ViewModel = function () {
var self = this;
self.myObjList = ko.observableArray();
self.sendItems = function() {
$.ajax({
type: "POST",
url: '/Xyz/Save',
data: ko.toJSON(self),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
},
error: function (request, status, error) {
alert(request.statusText);
}
});
}
}
var vm = new ViewModel()
ko.applyBindings(vm);
I do get the data if I pass the data as JSON.stringify({jsondata:ko.toJSON(self)}), but how do I then convert it into a object so that I can iterate over the myObjList and the parameters?
First of all try changing your Model to something like this :-
[JsonObject(MemberSerialization.OptIn)]
public class Test
{
[JsonProperty("myId")]
public string Id { get; set; }
[JsonProperty("parameters")]
public List<string> Parameters { get; set; }//List<string> or whatever it takes int of string
}
if it doesn't work, the please post your Ajax request data... Else....
I follow approach like this:-
MODEL:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace MvcApplication4.Models
{
[JsonObject(MemberSerialization.OptIn)]
public class Test
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
}
CONTROLLER
//
// POST: /Testing/
[HttpPost]
public void Post(MvcApplication4.Models.Test request)
{
try
{
//DO YOUR STUFF
}
catch (Exception ex)
{
throw (ex);
}
}
AJAX Call:-
var json = {};
json = data.id;
json = data.name;
$.ajax({
type: "POST",
url: ""//Your URL,
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(json)
}).done(function (data) {
}).fail(function (request, error) {
});
OR make your AJAX call like
$.ajax({
type: "POST",
url: ""//Your URL,
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: ko.toJSON({ id: value1, name: value2 }),//Get value1 and value2 from you ko varables
}).done(function (data) {
}).fail(function (request, error) {
});

Pass raw html from view to controller

I want to pass raw html from view to controller. Iam trying to do it with jquery ajax request. Everything is ok until object with raw html passes to controller. What is my mistake?
Here is my model, controller and jquery.
Thank you.
Model
public class NewsEditionModel
{
public string Title { get; set; }
public string SubTitle { get; set; }
public string Text { get; set; }
}
Controller
public ActionResult AddText(NewsEditionModel obj)
{
var news = new News();
try
{
news.Text = obj.Text;
news.PublishDate = DateTime.Now;
news.Title = obj.Title;
var repository = new Repository();
var success = repository.AddNews(news, User.Identity.Name);
return Json(new {data = success});
}
catch (Exception)
{
return View("Error");
}
}
Jquery
function submitForm() {
var text = ste.getContent();
var title = $('#title').val();
var obj1 = JSON.stringify({ Text: text, Title: title, SubTitle: "" });
var obj = $.parseJSON(obj1);
$.ajax({
type: "POST",
dataType: "json",
content: "application/json",
data: {obj: obj},
url: '#Url.Action("AddText", "News")',
success: function (res) {
}
});
}
Just add <ValidateInput(False)> _ to your contoller post req.
You can use this example
$.ajax({
url: '#Url.Action("AddText", "News")',
data: {obj: JSON.stringify({ Text: text, Title: title, SubTitle: "" })},
contentType: 'application/json',
dataType: 'json',
success: function (data) { alert(data); }
});
I guess instead of this:
data: {obj: obj},
you should do it like this:
data: {obj: JSON.stringify({ Text: text, Title: title, SubTitle: "" })},

Resources