繁体   English   中英

剃须刀的@ Html.Action

[英]@Html.Action for Razor

我正在尝试在asp.net mvc 3应用程序中为我的dropdownlistbox创建一个partialview。 在我的页面中,我有:

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

控制器partialview:

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

有没有更好的模板化Dropdownlistbox的方法?

我将在控制器中填充数据,然后将其传递给模型,最后使用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帮助器创建一个下拉列表。

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

我是在记事本中编写的,因此可能存在语法错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM