Asp.net

ASP.NET MVC 是發布模型 ID 的更好方法嗎?

  • June 22, 2012

我有一個綁定到視圖的 ViewModel:

ProductViewModel model = Mapper.Map<Product, ProductViewModel>(product);
return View(model);

視圖(和視圖模型)用於編輯,Product因此ProductViewModel具有與數據庫中的 ID 對應的 ID 屬性。

並將 ID 發布回控制器,我在視圖上的表單中執行此操作:

@Html.HiddenFor(x => x.Id)

即使這可行- 我想知道是否有更好的方法將 ID 發布回控制器?路線值可能嗎?或者這是一個相當標準的模式/方法?

如果我有一個在我的路由中包含 id 的 GET 操作:/Products/Edit/1那麼我通常將其保留為路由值:

[HttpPost]
public ActionResult Edit(int id, EditProductViewModel model)

不過,這純粹是我的偏好。沒有正確或錯誤的方法來做到這一點。

這個方法的好處是你不再需要使用 Hidden 值來傳遞它,因為它是 URL 的一部分。實際上,如果您確實使用 Hidden 值傳遞它,我相信它將被忽略。

或者,由於 id 是路由的一部分,您甚至不需要單獨的參數:

[HttpPost]
public ActionResult Edit(EditProductViewModel model)

public class EditProductViewModel 
{
   public int Id { get; set; }
}

同樣,這純粹是一種偏好。

引用自:https://stackoverflow.com/questions/11156889