将JSON数据映射到模型并返回MVC 4

时间:2012-12-21 04:57:53

标签: c# json asp.net-mvc-4

请原谅我可能做的任何错误说法。我只是在学习asp.net c#,OOP和MVC 4。

我在我的网站上使用Annotator插件,我正在尝试存储和检索数据库中的结果。创建新注释时,它会向控制器发送此类信息。

 {
      "text":"asdas sd a dasd as dasd",
      "ranges":
       [{
             "start":"/div/p[3]",
             "startOffset":195,
             "end":"/div/p[3]",
             "endOffset":532
       }],
       "quote":"Some quote that was selected.",
       "UserID":"1",
       "ProjectDocID":"1"
 }

现在,我希望像这样的东西可以将所有数据加载到一个简单易用的对象中。

 // GET: /Annotation/Create

    public ActionResult Create(Comment comment)
    {
        db.Comments.Add(comment);
        db.SaveChanges();
        return Json(comment);
    }

我看起来像这样的模型(我改变它,但需要更改)。

public class Comment
{
    [Key]
    public int CommentID { get; set; }
    public int ProjectDocID { get; set; }
    public int UserID { get; set; }

    public string text { get; set; }
    public string Annotation { get; set; }
    public string quote { get; set; }
    public string start { get; set; }
    public string end { get; set; }
    public string startOffset { get; set; }
    public string endOffset { get; set; }
    public DateTime DateCreated { get; set; }

    public virtual ICollection<CommentVote> CommentVote { get; set; }
    public virtual ICollection<CommentReply> CommentReply { get; set; }

    public ProjectDoc ProjectDoc { get; set; }
    public virtual User User { get; set; } 
}

从服务器获取数据并将其映射到模型需要做什么。我还需要能够以顶部的格式将其发回,以便插件在从控制器中的“详细信息”操作中请求时理解它。

1 个答案:

答案 0 :(得分:1)

不确定这是否是正确的方法,但它允许我将其存储在数据库中,这一切都很重要。我更新了我的模型如下。

public class Comment
{
    [Key]
    public int CommentID { get; set; }
    public int ProjectDocID { get; set; }
    public int UserID { get; set; }
    public string text { get; set; }
    public string quote { get; set; }
    public DateTime DateCreated { get; set; }

    public virtual ICollection<CommentVote> CommentVote { get; set; }
    public virtual ICollection<CommentReply> CommentReply { get; set; }
    public ProjectDoc ProjectDoc { get; set; }
    public virtual User User { get; set; }
    public List<ranges> ranges { get; set; }
}
public class ranges {
    public int ID { get; set; }
    public string start { get; set; }
    public string end { get; set; }
    public string startOffset { get; set; }
    public string endOffset { get; set; }


}

这与我使用Ajax发送到控制器的JSON对象相匹配。一旦它完全匹配上面的控制器动作。