【问题标题】:Passing value to each model in ASP.NET MVC将值传递给 ASP.NET MVC 中的每个模型
【发布时间】:2020-08-18 03:50:09
【问题描述】:

你能向我解释一下这两个的区别吗?因为当我想从某些模型向模型传递值但无法生成 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);   
}

【问题讨论】:

  • 你现在得到的 ID 值是多少?您要生成哪个 ID?
  • @ChetanRanpariya 脚本第一个 ID 为空,但第二个脚本通过共享点自动生成唯一 ID。
  • 同一个请求不同的输出
  • 检查Post(FolderModel是否从客户端传递ID

标签: c# asp.net-mvc asp.net-core asp.net-web-api


【解决方案1】:

您可以发布 Models 和 service.AddFolder() 的代码。

class FolderModel{

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

一般情况下,插入数据库后会自动generate ID

测试截图

控制器代码

    [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"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2011-05-08
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 2015-10-19
    相关资源
    最近更新 更多