2012-12-21 74 views
1

请原谅我可能做的任何错误行为。我只是学习asp.net c#,OOP和MVC 4.将JSON数据映射到模型并返回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; } 
} 

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

回答

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对象相匹配。一旦它完全匹配上面的控制器操作。

相关问题