2011-10-22 27 views
1

我想在我的asp.net mvc 3應用程序中爲我的dropdownlistbox創建一個partialview。 在我的網頁我有:@ Html.Action for Razor

@Html.Action("PopulateCombo","ComboController") 

控制器partialview:

public ActionResult PopulateCombo() 
{ 
    //some code here to organise data and maybe some caching 
    return ItemsForCombo; 
} 

有一個模板化的下拉框一個更好的辦法?

回答

0

我會在控制器中填充數據,然後將其傳遞給模型,最後使用Html.DropDownListFor。我的意思是,這就是MVC代表:)

(PS:它已經相當一段時間,因爲我不是在C#代碼了,所以道歉對任何錯字)

控制器。 CS

Public ActionResult() 
{ 
    Model m = new Model(); 
    //populate data into a list 
    m.Items = ... 

    return View(m); 
} 

model.cs

... 
Public List<object> Items { get; set; } 

index.cshtml

@using Model // I guess it was something like this 

// I cant remember the exact order of the arguments to dropdownlistfor, so just figure it out :) 
@Html.DropDownListFor (some arguments) 
0

您的要求是?部分視圖可以代表您可以在整個應用程序中重複使用的控件。我不認爲下拉式列表是部分視圖的好候選者。

如果我是你,我想顯示一個下拉列表,我會使用現有的HTML幫手。

在我的控制器中我將存儲值下拉列表視圖中的包:

IList<SelectListItem> selectListItems = new List<SelectListItem>(); 
// Populate selectListItems 
... 

// Create a select list. You'll have to replace dataValueField and dataTextField with property names 
SelectList mySelectList = new SelectList(selectListItems, "dataValueField", "dataTextField"); 

// Assume that select list contains a list of countries 
ViewBag.Countries = mySelectList; 

那麼在您看來,您可以創建HTML幫助

@Html.DropDownListFor(m => m.CountryId, (SelectList) ViewBag.Countries); 

我一個下拉列表寫在記事本中,所以可能會出現語法錯誤。