I need to post JSON data from the client to the application ASP.NET MVC 4, but the javascript code is run by user and transfer data from the site www.lotsalneschs.com to my server. For testing I used Google Chrome console panel. Controller code:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Save(List<NewsModel> items)
{
return Json(null);
}
}
public class NewsModel
{
public string Title { get; set; }
public string Content { get; set; }
public List<string> Tags { get; set; }
}
Javascript code:
function News() {
var arr = {};
var title = "items";
var tTitle = "Title";
var cTitle = "Content";
var tgTitle = "Tags";
arr[title] = [];
for (var i = 0; i < 10; i++) {
var n = {};
n[tTitle] = "Title №" + i;
n[cTitle] = "TEXT";
n[tgTitle] = [];
for (var j = 0; j < 5; j++) {
n[tgTitle].push("tag" + j);
}
arr[title].push(n);
}
return arr;
}
var news = News();
$.ajax({
url: 'http://localhost:28369/Home/Save',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(news)
});
If I execute the script while being on the page localhost:28369/Home/Index everything works perfectly:
https://i.stack.imgur.com/RL1nR.png
But the execution of this script on any other page, for example stackoverflow.com does not break at the same breakpoint. If I delete contentType in the script, get the following:
https://i.stack.imgur.com/4Hcyn.png
If I delete contentType and not use JSON.stringify to format my data, get the following:
https://i.stack.imgur.com/F1Ql7.png
How to fix this problem?