简体   繁体   English

将值传递给 ASP.NET MVC 中的每个 model

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

Can you explain to me the difference about 2 of this.你能向我解释一下这两个的区别吗? Because I have problem when I want to pass values to models from some models but it can't generate an ID.因为当我想从某些模型向模型传递值但无法生成 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);
}

But when I'm using this it works and want to generate ID:但是当我使用它时它可以工作并且想要生成 ID:

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

You could post the codes of Models and service.AddFolder().您可以发布模型和 service.AddFolder() 的代码。

class FolderModel{

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

Normally, it will generate ID automatically after insert to DB.通常情况下,它会在插入数据库后自动生成 ID

Screenshots of test测试截图

在此处输入图像描述

Codes of controller 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);

    }

Body of Post帖子正文

{
   "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