Angular $ http发布到MVC操作,参数为null

时间:2022-09-25 14:38:30

So I do this post:

所以我发这个帖子:

$http.post(Common.blog.save, { blog: blog })
    .then(saveBlogComplete)
    .catch(function(message) {

    });

And I get this in fiddler output:

我用小提琴输出得到这个:

{"blog":{"title":"Chicken Is Good","content":"#Chicken Is Good\n##Contents\n* Introduction\n* Factfile\n* Analysis\n* Evaluation\n* Conclusion\n###Introduction\n\n###Factfile","dateAuthored":"","userId":""}}

In my action:

在我的行动中:

[HttpPost]
public JsonResult Save(string blog)
{
    var desBlog = JsonConvert.DeserializeObject<BlogDto>(blog);

    return this.ExecuteService(() => this.blogService.Save(desBlog));
}

string blog is coming back null.... I'm not sure why this is happening?

字符串博客回来了......我不确定为什么会这样?

I have done the following

我做了以下事情

  • Put breakpoint in JavaScript - data is getting populated
  • 在JavaScript中放置断点 - 数据正在填充

  • Reviewed Fiddler output - the data is the same as JavaScript obj
  • 评论了Fiddler输出 - 数据与JavaScript obj相同

  • Put breakpoint in the Action - it's getting called, the HttpContext doesn't have any data about the POST data in it
  • 把断点放在Action中 - 它被调用,HttpContext没有关于POST数据的任何数据

2 个解决方案

#1


2  

Your code will work without stringify function, if you change your mvc action parameter from String to Blog:

如果将mvc action参数从String更改为Blog,则代码将在没有stringify函数的情况下工作:

public class Blog
{
   public string Title {get; set;}
   public string Content {get; set;}
   public DateTime DateAuthored {get; set;}
   public long UserId {get; set;}
}

[HttpPost]
public JsonResult Save(Blog blog)
{

This happening because your blog model on server-side doesn't match to the structure of passing parameter from angular.

发生这种情况是因为服务器端的博客模型与从angular传递参数的结构不匹配。

#2


0  

I just needed to stringify the data!

我只需要对数据进行字符串化!

$http.post(Common.blog.save, { blog: JSON.stringify(blog) })
    .then(saveBlogComplete)
    .catch(function(message) {

    });

#1


2  

Your code will work without stringify function, if you change your mvc action parameter from String to Blog:

如果将mvc action参数从String更改为Blog,则代码将在没有stringify函数的情况下工作:

public class Blog
{
   public string Title {get; set;}
   public string Content {get; set;}
   public DateTime DateAuthored {get; set;}
   public long UserId {get; set;}
}

[HttpPost]
public JsonResult Save(Blog blog)
{

This happening because your blog model on server-side doesn't match to the structure of passing parameter from angular.

发生这种情况是因为服务器端的博客模型与从angular传递参数的结构不匹配。

#2


0  

I just needed to stringify the data!

我只需要对数据进行字符串化!

$http.post(Common.blog.save, { blog: JSON.stringify(blog) })
    .then(saveBlogComplete)
    .catch(function(message) {

    });