Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Net MVC-参数与模型值的绑定!_C#_Asp.net_Asp.net Mvc - Fatal编程技术网

C# Net MVC-参数与模型值的绑定!

C# Net MVC-参数与模型值的绑定!,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,这似乎是模型绑定给我带来的问题 本质上,我有一个名为ProductOption的模型,对于这个问题,它有两个字段 ID(Int)PK ProductID(Int)FK 我有一个标准的路线设置 context.MapRoute( "Product_default", "Product/{controller}/{action}/{id}", new { controller = "Product", action = "Index", id

这似乎是模型绑定给我带来的问题

本质上,我有一个名为ProductOption的模型,对于这个问题,它有两个字段

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) %>

我已经通过更新我的路线解决了这个问题(并不完全满意,但它确实有效)


我认为正在设置
id
参数,因为默认情况下,您的路线会设置它。在控制器内部,您正在ProductID的ViewModel中设置一个附加参数,这可能始终等于ID参数,因为两者基本上都设置为QueryString/GET参数。(在本例中为1)

当您阻止路由分配ID参数时,您更改路由的修复方法会起作用,这似乎是一个不错的选择,但可能并不理想-这取决于您想要解决问题的方式:

context.MapRoute(
  "Product_addoptionalextra",
  "Product/{controller}/Add/{ProductID}",
  new { controller = "Product",action="Add", ProductID = UrlParameter.Optional }
);
或者,重新安排变量,使ID实际上是相关的ProductID,然后可以使用表示ID的OtherID

如果你有MVC2,我可能会建议你用它来解决这个问题。虽然我不知道您的
ProductViewModel
,但我假设它里面有ID。如果设置适当的模板,几乎可以忽略可能重叠的ID

public class ProductExtraModel
{
   //Database 
  public int ID { get; set; }
  public string Name { get; set; }

  [UIHint("Product")]
  public ProductModel Product { get; set; }
}

当使用
productExtraViewModel.product.ID
将模型传回控制器时,您将能够访问产品ID,并且您的普通ID仍将在
productViewModel.ID

上可用。您的代码暗示它在模型中称为ProductID而不是.ID?您可以发布视图模型代码吗?请参阅Alex的帖子那样做
context.MapRoute(
  "Product_addoptionalextra",
  "Product/{controller}/Add/{ProductID}",
  new { controller = "Product",action="Add", ProductID = UrlParameter.Optional }
);
public class ProductExtraModel
{
   //Database 
  public int ID { get; set; }
  public string Name { get; set; }

  [UIHint("Product")]
  public ProductModel Product { get; set; }
}