@Html.剃刀行动

本文关键字:剃刀 @Html | 更新日期: 2023-09-27 18:12:08

我试图在我的asp.net mvc 3应用程序中为我的下拉列表框创建一个局部视图。在我的页面我有:

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

控制器partialview:

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

是否有更好的方式模板下拉列表框?

@Html.剃刀行动

我将在控制器中填充数据,然后将其传递给模型,最后使用Html.DropDownListFor。我的意思是,这就是MVC的意思:)

(PS:我已经有一段时间没有用c#编写代码了,所以我为任何类型的错别字道歉)

controller.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)

你的需求是什么?部分视图可以表示可以在整个应用程序中重用的控件。我不认为下拉列表是局部视图的好选择。

如果我是你,我想显示一个下拉列表,我会使用现有的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 helper

创建一个下拉列表
@Html.DropDownListFor(m => m.CountryId, (SelectList) ViewBag.Countries);

我用记事本写的,所以可能有语法错误