2012-11-22 22 views
0

我剛剛進入MVC,我堅持一個我認爲會相對簡單的概念。MVC 4 - 在同一頁面上返回子細節

所以,我有一個表格,其中職位,以一個控制器(這是好的),在一分鐘我:

控制器

public ActionResult TestAction(int productId) 
{ 
    // What to do here... ? 
    return View(); 
} 

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult TestAction(FormCollection values) 
{ 
    // Do work here and return the objects 
    return View(Products); 
} 

查看

@foreach (var product in Model) 
      { 
       <tr> 
        <td>@product.Provider.Name</td> 
        <td>&pound;@product.MonthlyPremium</td> 
        <td>@Html.ActionLink("More Details", "TestAction", new { productId = product.ProductId })</td> 
        <td>Compare</td> 
       </tr> 
      } 

// I want the singular product details to be displayed here, under the product list... but how?! 

現在,我想要的是,當你點擊「更多細節」(ActionLink),然後產品細節將會被顯示,這是單數產品對象的一部分。我從GET調用了TestAction控制器,但是如何保留產品的視圖並顯示單數產品的詳細信息?將此單數產品分配給ViewBag並以此方式進行操作?那麼,對於產品列表,請緩存原始列表並使用該緩存?

我想通過回發完成此操作,因爲這是針對我的網站的非JS版本。

當然,必須有更好的方法來做到這一點,或者我被ViewState寶寶長時間了?

回答

1

您可以將屬性添加到您的模型,例如bool ViewDetail,並設置在您的控制器對應於productId參數項:

public ActionResult TestAction(int productId) 
{ 
    // TODO: error checking 
    Products.Single(m => m.ProductId == productId).ViewDetail = true; 
    return View(Products); 
} 

並在您的視圖中顯示它:

var productDetail = Model.SingleOrDefault(m => m.ViewDetail == true); 
if (productDetail != null) 
{ 
    // Display product details 
} 

或者你可以改變你的模型,包含:

public class ProductsWithDetailModel 
{ 
    public IEnumerable<Product> Products { get; set; } // to loop over and display all products 
    public Product DetailProduct { get; set; }   // to display product details, if not null 
} 

然後,再次根據productId參數設置DetailProduct,並在視圖中顯示它(如果它不爲空)。

+0

這是一種在單一視圖內查看項目詳情的實踐方法嗎?這兩種方法都涉及我修改我的模型層,並仍然從緩存中獲取所有原始產品列表? –

+0

@thedixon您想要根據以前的輸入顯示模型列表和該列表中的特定項目。無論如何,您必須確定要顯示哪個項目。你可以在'ViewBag'中設置'productId',但是你的視圖中會有更多的邏輯,我個人試圖阻止。我傾向於將模型視爲視圖模型,因此如果需要,您可以爲每個視圖創建特定模型。這就是說,我喜歡第二種方法,因爲它不會混淆產品模型。 – CodeCaster

+1

謝謝@CodeCaster,具有諷刺意味的是,我原本以爲這樣做,但認爲會有一個聰明的MVC方式來做到這一點。再次感謝您對此的幫助。 –