【问题标题】:Bind a ViewBag in an @Html.DropDownList inside of a WebGrid in MVC在 MVC 中的 WebGrid 内的 @Html.DropDownList 中绑定 ViewBag
【发布时间】:2015-03-31 04:16:18
【问题描述】:

自上周以来,我阅读了很多帖子,但没有任何关于我的问题。

我有这个简单的控制器:

public class HomeController : Controller
{
    private AdventureWorks2014Entities db = new AdventureWorks2014Entities();

    public ActionResult Index()
    {
        var model = db.Products.ToList();
        ViewBag.Products = new SelectList(db.Products, "ProductID", "Name");
        return View(model);
    }
}

还有这个简单的视图:

@model IEnumerable<ADWork.Client.Models.Product>

@{
    var grid = new WebGrid(Model);
}

@grid.GetHtml(
    columns: grid.Columns(
        grid.Column("ProductID"),
        grid.Column("Name", null, format:@<span>@Html.DropDownList("Products", @item.Name, new { style = "color:red;" }) </span>),
            grid.Column("ListPrice", "Price")
    )
)

现在的问题是 DropDownList。我可以像这样轻松渲染它:

 @Html.DropDownList("Products", null , new { style = "color:red;" }) 

但我想添加@item.Name 以显示默认字符串,这就是问题所在,@HTML.DropDownList 内的@(at 符号)不起作用,它不是黄色的,它就像关闭一样,因为行首的@就像我在开头发布的那样。

任何想法如何在不创建新的 SelectList(blah blah) 的情况下解决这个问题,只需将 @item.Name 转换为字符串?

【问题讨论】:

  • 你不需要 at,因为你已经在代码块中了。
  • @ErikFunkenbusch,我很久以前就试过了,但它不起作用:编译器错误消息:CS1973:'System.Web.Mvc.HtmlHelper'没有名为'DropDownList'的适用方法,但是似乎具有该名称的扩展方法。扩展方法不能动态调度。考虑强制转换动态参数或在没有扩展方法语法的情况下调用扩展方法。就像我说的,我尝试了很多东西,但它不起作用
  • 你去吧。你不能在这样的助手中使用动态。在它前面放一个@ 不会改变任何东西。您需要先将值复制到局部变量,然后在帮助程序中使用该局部变量。

标签: c# asp.net-mvc drop-down-menu webgrid


【解决方案1】:

经过 6 天的尝试和尝试后找到解决方案!!!!!!!!!!!!

@grid.GetHtml(
    columns: grid.Columns(
        grid.Column("ProductID"),
        grid.Column("Name", null, format:
            @<span>
               grid.Column("Name", null, format:
@<span>
    @{
            string name = (@item.Name).ToString();
            @Html.DropDownList("Products", null, name , new { style = "color:red;" });
    }
</span>),
           </span>),
            grid.Column("ListPrice", "Price")
    )
)

我必须用@item.Name 创建一个新字符串,仅此而已!!! ufff 我看到了很多帖子,人们在那里创建了一个 ViewBag,然后在 DropDOwnList 中创建了一个新列表,这没有意义......这就是答案!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多