将ViewBag作为参数传递
本文关键字:参数传递 ViewBag | 更新日期: 2023-09-27 18:17:13
如果我在动态ViewBag
中有一个值,为什么我不能把它传递给一个方法?为了简单起见,假设我有ViewBag.SomeValue
,我想把ViewBag.SomeValue
传递给HTML Helper。如果HTML助手接受动态作为一个变量,为什么不接受我的ViewBag.SomeValue
?
@Html.SimpleHelper(ViewBag.SomeValue)
public static string SimpleHelper(this HtmlHelper html, dynamic dynamicString)
{
return string.Format("This is my dynamic string: {0}", dynamicString);
}
错误消息告诉您,扩展方法不能动态分派。只是。net不支持它。它与ASP无关。NET MVC或Razor。尝试为接受动态参数的类型编写扩展方法,然后尝试调用此扩展方法,并向其传递动态变量,您将获得编译时错误。
考虑下面的控制台应用程序示例,它说明了这一点:
public static class Extensions
{
public static void Foo(this object o, dynamic x)
{
}
}
class Program
{
static void Main()
{
dynamic x = "abc";
new object().Foo(x); // Compile time error here
}
}
所以你需要转换:
@Html.SimpleHelper((string)ViewBag.SomeValue)
实际上,正如Adam所说,你需要使用强类型的视图模型,永远不要使用ViewBag。这只是无数不应该使用ViewBag的原因之一。
更重要的是,因为ViewBag是一个不好的做法,因为魔术字符串作为属性在ViewBag -你试图发送什么给它。也许有更好的方法?您应该能够使用helper实例通过以下方式引用它:
helper.ViewContext.Controller.ViewBag
,但我不是一个使用ViewBag除了标题http://completedevelopment.blogspot.com/2011/12/stop-using-viewbag-in-most-places.html
我知道这是一个老问题,但这是我在搜索这个问题时出现的。
通过简单地将ViewBag列为方法中的动态参数,将其作为参数传递很容易。例如,下面是我如何将ViewBag传递到我的一个助手类中进行列排序。
public static IEnumerable<Models.MyViewModel> MyMethod(IEnumerable<Models.MyViewModel> model, string sortOrder, dynamic ViewBag)
我创建了一个扩展方法
public static IHtmlContent BindDropdown(this IHtmlHelper htmlHelper, SelectList viewBag)
{
StringBuilder sb = new StringBuilder();
foreach (var item in viewBag)
{
sb.Append("<option value='"" + item.Value + "'">" + item.Text + " </option>");
}
return new HtmlString(sb.ToString());
}
和下面在Razor页面使用的一样。
<select>@Html.BindDropdown((SelectList)ViewBag.Currency) </select>
在控制器端,我的下拉ViewBag是
ViewBag.Currency = new SelectList(_currencyService.GetAll().Select(i => new { i.Id, Name = i.Code }).ToArray(), "Id", "Name");