2017-04-16 28 views
0

所以我有这个CSHTML:表单POST参数返回查看错后产生

@using (Html.BeginForm("DeleteProduct", "Shop", FormMethod.Post)) 
{ 
    @Html.Hidden("productId", product.ProductId); 
    @Html.Hidden("productVariantId", product.ProductVariantId); 
    @Html.Hidden("quantity", product.Quantity); 
    <button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button> 
} 

调用此后端:在控制器

[HttpPost] 
public ActionResult DeleteProduct(int productId, int? productVariantId, int quantity) 
{ 
    //...product gets deleted, etc. Not important for this question 

    //regenerate the view, same as when loading the 'Order' view initially 
    OrderWrapperViewModel model = GenerateOrderWrapperModel(); 
    return View("Order", model); 
} 

加载顺序图如下所示:

[HttpGet] 
public ActionResult Order() 
{ 
    OrderWrapperViewModel model = GenerateOrderWrapperModel(); 
    return View(model); 
} 

当我第一次致电删除时,我删除了一个ID为:7和产品变体ID:的产品。一切正常。但是,返回页面后,产品ID 7不再列出,只有产品ID 1。所以第二次产品ID:1和产品变种ID:4

当从DeleteProduct返回时,该URL当前显示/ Shop/DeleteProduct。当我调试通过剃刀代码:

generate form

似乎是正确的,对不对?

好了,HTML是不同的:

different html

当然,点击按钮通过这些不正确的参数也是如此。我可以向你保证,这是同一个按钮,当时只显示1个产品。

我解决了它通过简单的重定向到Order视图再次,所以我更感兴趣为什么这种情况发生。原因是,因为对于其他人,我将返回错误消息(使用ModelState)。当我重定向时,这当然不起作用。

它也发生在生产环境中。

+0

正确的做法是按照PRG模式进行操作。但对于行为的解释,请参阅[TextBoxFor显示初始值,而不是从代码更新的值](http://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated - 从代码/ 26664111#26664111) –

回答

2

这是预期的行为,当您试图改变Model就像你在DeleteProduct天色渐老值的原因做了值,因为当您返回到相同的看法,从ModelState值首先呈现这种情况,所以如果ModelState是空的,将填充从Model值,所以这就是为什么我们使用

ModelState.Clear(); 

如果您在Model,你必须首先从ModelState清除值更改值。你可以把一个断点,并检查keyvalue它看起来像这样

enter image description here

1

DeleteProduct执行这样的操作通常使用的方法是重定向到另一个动作删除完成后:

[HttpPost] 
public ActionResult DeleteProduct(int productId, int? productVariantId, int quantity) 
{ 
    //...product gets deleted, etc. Not important for this question 

    return RedirectToAction("Order"); 
} 

通过这种方式,您可以在Order方法中获得新的ModelState,以便它不会与您传递给视图的任何Model参数发生冲突,并且用户在其浏览器中看到“更正确”的URL产品被删除(例如/Shop/Order而不是/Shop/DeleteProduct)。