gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 2 使用 POST 创建模型

转载 作者:行者123 更新时间:2023-12-01 09:38:42 25 4
gpt4 key购买 nike

我有以下型号:

public class Product {
public int Id { get; set; }
public string Name { get; set; }
private int CategoryId { get; set; }
public Category Category { get; set; }
public string InventoryDetails { get; set; }
}

我的 Controller 中有一个用于创建新产品的操作。我的问题是如何限制可以从 POST 数据绑定(bind)的模型的属性?因为我只希望用户 POST 数据绑定(bind) Name 和 CategoryId。还是创建一个只有这些属性可以绑定(bind)的单独 View 模型更好?

public ActionResult Create(Product p)

public ActionResult Create(CreateProductViewModel model)

在哪里

public class CreateProductViewModel {
public string Name {get; set;}
public int CategoryId {get;set;}
}

最佳答案

使用 View 模型。这将使您的 View 与数据模型分离。正如您发现的那样,它们并不总是具有相同的需求,并且模型应该特定于 View 。您可以手动映射属性或使用 AutoMapper用于更复杂的场景。

关于asp.net-mvc - ASP.NET MVC 2 使用 POST 创建模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3397815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com