2011-10-22 69 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); 

我一个下拉列表写在记事本中,所以可能会出现语法错误。