簡體   English   中英

將值傳遞給 ASP.NET MVC 中的每個 model

[英]Passing value to each model in ASP.NET MVC

你能向我解釋一下這兩個的區別嗎? 因為當我想從某些模型向模型傳遞值但無法生成 ID 時遇到問題。

[HttpPost]
public HttpResponseMessage CreateShortcut([FromBody]ShortcutModel shortcut)
{
    var service = new DocumentService();
    FolderModel folders = new FolderModel
    {
        Title = shortcut.Title,
        ParentID = shortcut.ParentID,
        HeaderTitle = shortcut.HeaderTitle,
        HeaderReferenceNo = shortcut.HeaderReferenceNo,
        ItemType = shortcut.type,
        idreference = shortcut.idreference,
        ReferenceNo = shortcut.ReferenceNo
    };
    FolderModel newFolder = service.AddFolder(folders);
    return Request.CreateResponse(HttpStatusCode.OK, newFolder);
}

但是當我使用它時它可以工作並且想要生成 ID:

public HttpResponseMessage Post(FolderModel folder)
{
    var service = new DocumentService();
    FolderModel newFolder = service.AddFolder(folder);
    return Request.CreateResponse(HttpStatusCode.OK, newFolder);   
}

您可以發布模型和 service.AddFolder() 的代碼。

class FolderModel{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
     
    ...
}

通常情況下,它會在插入數據庫后自動生成 ID

測試截圖

在此處輸入圖像描述

controller的代碼

    [Route("/addfolder")]
    [HttpPost]
    public HttpResponseMessage CreateShortcut([FromBody] ShortcutModel shortcut)
    {
        //var service = new DocumentService();
        FolderModel folders = new FolderModel
        {
            Title = shortcut.Title,
            ParentID = shortcut.ParentID,
            HeaderTitle = shortcut.HeaderTitle,
            HeaderReferenceNo = shortcut.HeaderReferenceNo,
            ItemType = shortcut.type,
            idreference = shortcut.idreference,
            ReferenceNo = shortcut.ReferenceNo
        };
        service.Folders.Add(folders);

        service.SaveChanges();

        int ID = folders.ID;
        //return Request.CreateResponse(HttpStatusCode.OK, newFolder);
        return new HttpResponseMessage(HttpStatusCode.OK);

    }

帖子正文

{
   "Title":"1",
   "ParentID":"2",
   "HeaderTitle":"3",
   "HeaderReferenceNo":"4",
   "type":"5",
   "idreference":"6",
   "ReferenceNo":"7"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM