【发布时间】:2026-02-08 15:45:02
【问题描述】:
这似乎是模型绑定引起了我的问题。
基本上我有一个名为 ProductOption 的模型,就这个问题而言,它有 2 个字段
ID (Int) PK ProductID (Int) FK
我有一个标准路线设置
context.MapRoute(
"Product_default",
"Product/{controller}/{action}/{id}",
new { controller = "Product", action = "Index", id = UrlParameter.Optional }
);
如果用户想添加一个选项,则 URL 是,
/产品/选项/添加/1
在上面的 URL 中 1 是 ProductID,我有下面的代码来返回一个空白模型的视图,
[HttpGet]
public ActionResult Add(int id)
{
return View("Manage", new ProductOptionModel() { ProductID = id });
}
现在在我看来,我保留了一个隐藏字段
<%= Html.HiddenFor(x=>x.ID) %>
这用于确定(提交时)我们是否正在编辑或添加新选项。然而,.net 中的模型绑定器似乎将 .ID(离开上述 get actionresult 时为 0)替换为 1(或 URL 中 id 参数的值)
我怎样才能停止或解决这个问题?
视图模型
public class ProductExtraModel
{
//Database
public int ID { get; set; }
public string Name { get; set; }
public int ProductID { get; set; }
public ProductModel Product { get; set; }
}
【问题讨论】:
-
您的代码暗示它在模型中称为 ProductID 而不是 .ID?
-
能贴出视图模型代码吗?
-
看看 Alex 的帖子这样做是有意义的
标签: c# asp.net asp.net-mvc