简体   繁体   English

ASP.NET MVC 4-将JSON数据从客户端的任何页面发布到服务器

[英]ASP.NET MVC 4 - posting JSON data from any page on the client side to the server

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. 我需要将JSON数据从客户端发布到应用程序ASP.NET MVC 4,但是javascript代码由用户运行,并将数据从网站www.lotsalneschs.com传输到我的服务器。 For testing I used Google Chrome console panel. 为了进行测试,我使用了Google Chrome控制台面板。 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: JavaScript代码:

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: 如果我在页面localhost:28369 / Home / Index上执行脚本,则一切运行正常:

http://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. 但是该脚本在其他任何页面(例如stackoverflow.com)上的执行不会在同一断点处中断。 If I delete contentType in the script, get the following: 如果我在脚本中删除contentType,请获取以下内容:

http://i.stack.imgur.com/4Hcyn.png

If I delete contentType and not use JSON.stringify to format my data, get the following: 如果删除contentType而不使用JSON.stringify格式化数据,请获取以下内容:

http://i.stack.imgur.com/F1Ql7.png

How to fix this problem? 如何解决这个问题?

I think it has to do with your URL being hard coded to localhost. 我认为这与您的URL硬编码到localhost有关。 Try replacing your line 尝试更换线

url: 'http://localhost:28369/Home/Save',

with

url: '@Url.Action("Save", "Home")',

Edit: 编辑:

Thinking about it you should see what path is generated by the Url.Action. 考虑一下它,您应该看到Url.Action生成了什么路径。 I think the issue is being run from a different server local host is pointing to that server and not your computer. 我认为问题是从另一台服务器本地主机运行的,该主机指向该服务器而不是您的计算机。 If the Url.Action doesn't work then you should point it to a public facing address. 如果Url.Action不起作用,则应将其指向面向公众的地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM