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

相關問題