Telerik MVC Grid:如何在列中使用 DropDownList?

2023-12-01

我有一个 Telerik MVC 网格,位于带有 Razor 的 MVC 3 应用程序中,它是 Ajax 绑定的。我现在尝试向其中添加一个下拉列表列,以便用户可以在编辑模式下使用它,但不知道如何操作。网格显示产品列表,我希望下拉列表包含可以将产品关联到的 ProductCategories 集合。我已经研究了好几个小时了,但我没有任何想法。我真的希望这里有人能提供帮助:)

我一直在参考 Telerik 演示,它位于here.

我认为让我困惑的部分是演示使用的帮助视图。在演示中,这称为“ClientEmployee(Editor)”。就我而言,我已将助手放置在名为“ProductCategoryDropList.cshtml”的文件中。在此帮助程序中,我很难正确绑定 DropDownList。我认为这可能是因为我没有以某种方式使用正确的数据设置 BindTo() 方法。我在下面的示例 DropDownList Helper 代码中标记了这一混淆点,并使用“SomeCollectionReference”作为“new SelectList()”构造函数调用中的第一个参数。当我尝试将“模型”放在该位置时,出现 NullReferecne 异常。当我尝试访问包含列表的 ViewBag 数据时,我收到一条类似于“SelectList 没有 ProductCategoryID 列”或类似内容的消息。所以,我不确定还可以尝试什么。

我不确定对我的问题的描述有多清楚,但为了完整起见,我在下面包含了我认为相关的代码。

控制器:

public ActionResult Index()
{
    ViewBag.ProductCategories = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductcategoryName");
    var products = _productService.GetProducts().ToList();
    var presentationModel = _mapper.MapAsList(products);
    return View(presentationModel);
}

//
// GET: /Product/
[GridAction]
public ViewResult _Index()
{
    ViewBag.ProductCategories = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductcategoryName");
    return View(new GridModel<ProductPresentationModel>
                    {
                        Data = _mapper.MapAsList(_productService.GetProducts().ToList())
                    });
}

View:

这有点长,但我尝试通过将“//

@model IEnumerable<Models.PresentationModels.ProductPresentationModel>

@(Html.Telerik().Grid(Model).HtmlAttributes(new { style = "width: 100%;" })
        // Give the Grid an HTML id attribute value
        .Name("ProductGrid")
        // Establish the promiry key, to be used for Insert, Update, and Delete commands
        .DataKeys(dataKeys => dataKeys.Add(p => p.ProductID))
        // Add an Insert command to the Grid Toolbar
        .ToolBar(commands => commands.Insert().ButtonType(GridButtonType.ImageAndText))
        // Using Ajax Data Binding to bind data to the grid
        .DataBinding(dataBinding => dataBinding
                // Ajax Binding
                .Ajax()
                    .Select("_Index", "Product")
                    // Home.Insert inserts a new data record
                    .Insert("Create", "Product")
                    // Home.Update updates an existing data record
                    .Update("Edit", "Product")
                    // Home.Delete deletes an existing data record
                    .Delete("Delete", "Product")
        )
        .Columns(columns =>
        {
            columns.Bound(p => p.ProductName).Width(120);
            columns.Bound(p => p.ProductDescription).Width(150);
            columns.Bound(p => p.PricePerMonth).Width(120);
            columns.Bound(p => p.ProductImagePath).Width(150)
            columns.Bound(p => p.ProductActive).Width(120)
                .ClientTemplate("<input type='checkbox' disabled='disabled' name='Active' <#= ProductActive ? checked='checked' : '' #> />");
            columns.Bound(p => p.ProductCategoryName); // <--- DropList Here
            columns.Command(commands =>
            {
                commands.Edit().ButtonType(GridButtonType.Image);
                commands.Delete().ButtonType(GridButtonType.Image);
            });
        })
        .Editable(editing => editing.Mode(GridEditMode.PopUp))
        .ClientEvents(events => events.OnEdit("onEdit"))
        .Pageable()
        .Scrollable()
        .Sortable()
        .Filterable()
)

@section HeadContent {
    <script type="text/javascript">
        function onEdit(e) {
            $(e.form).find('#ProductCategoryName').data('tDropDownList').select(function (dataItem) {
                return dataItem.Text == e.dataItem['ProductCategoryName'];
            });
        }
    </script>
}

Model:

[DisplayName(@"Category Name")]
[UIHint("ProductCategoryDropList"), Required]
[StringLength(255, ErrorMessage = @"Product Category Name cannot be more than 255 characters in length")]
public string ProductCategoryName
{
    get 
    {   
        string name = string.Empty;

        if (_model.ProductCategory != null)
        {
            name = _model.ProductCategory.ProductCategoryName;
        }

        return name;
    }
    set 
    {
        if (_model.ProductCategory != null)
        {
            _model.ProductCategory.ProductCategoryName = value;
        }
    }
}

下拉列表助手:

@model Models.PresentationModels.ProductPresentationModel

@(Html.Telerik().DropDownList()
        .Name("ProductCategoryName")
            .BindTo(new SelectList(<SomeCollectionReference>, "ProductCategoryID", "ProductCategoryName"))
)

产品映射器:

public List<ProductPresentationModel> MapAsList(List<Product> products)
{
    //var categoryList = new SelectList(_productCategoryService.GetProductCategories().ToList(), "ProductCategoryID", "ProductCategoryName"); 

    var presentationModels = products
            .Select(x => new ProductPresentationModel()
            {
                ProductID = x.ProductID,
                ProductCategoryID = ((x.ProductCategory != null) ? x.ProductCategory.ProductCategoryID : 0),
                ProductCategoryName = ((x.ProductCategory != null) ? x.ProductCategory.ProductCategoryName : String.Empty),
                ProductName = x.ProductName,
                ProductDescription = x.ProductDescription,
                PricePerMonth = x.PricePerMonth,
                ProductImagePath = x.ProductImagePath,
                ProductActive = x.ProductActive,
                ProductCategories = new SelectList(_productCategoryService.GetProductCategories().ToList(), "ProductCategoryID", "ProductCategoryName")//categoryList
            }).ToList();

    return presentationModels;
}

我设法解决了这个问题,但我仍然有一个问题。这是我为了让它工作而改变的:

在控制器中创建了一个 ViewData 对象,如下所示......

public ActionResult Index()
{
    // ViewData object here ...
    ViewData["ProductCategories"] = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductCategoryName");
    var products = _productService.GetProducts().ToList();
    var presentationModel = _mapper.MapAsList(products);
    return View(presentationModel);
}

//
// GET: /Product/
[GridAction]
public ViewResult _Index()
{
    // ViewData object here ...
    ViewData["ProductCategories"] = new SelectList(_productCategoryService.GetActiveProductCategories(), "ProductCategoryID", "ProductCategoryName");
    return View(new GridModel<ProductPresentationModel>
                    {
                        Data = _mapper.MapAsList(_productService.GetProducts().ToList())
                    });
}

然后,我在 DropDownList Helper 中使用了 ViewData 对象,如下所示......

@using System.Collections
@model Models.PresentationModels.ProductPresentationModel

@(Html.Telerik().DropDownList()
        .Name("ProductCategoryName")
        .BindTo(new SelectList((IEnumerable)ViewData["ProductCategories"], "Value", "Text"))
);

我现在的问题是......我必须使用 ViewData 对象吗?我希望能够使用我的模型中的属性。但是,由于某种原因,我的模型在帮助程序文件中始终为 NULL。而且,如果我尝试将 DropDownList 代码放入网格创建代码中,则 DropDownList 根本不起作用。

那么,我还有其他选择吗?

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Telerik MVC Grid:如何在列中使用 DropDownList? 的相关文章

  • 使用 Signalr 拥有类似 facebook 的通知系统

    我想在 ASP NET MVC 3 中实现一个类似 facebook 的通知系统 通知被发送到特定用户 以通知他对其某个项目进行操作 signalr适合这样的要求吗 我如何使用 SignalR 向特定用户 该用户的所有打开的会话 发送通知
  • 删除已从另一个下拉菜单中选择的下拉值

    我在网上搜索了一段时间 但仍然找不到答案 我的网站上有三个下拉菜单 我使用它们来接受用户首选项 以便用户可以控制结果的输出 所以我想知道如果在其中一个下拉列表中选择了该值 是否可以从其他两个下拉列表中取出该值 例如 如果用户在第一个电影中选
  • DropDownList 有一个无效的 SelectedValue,因为它不存在于项目列表中

    这是场景 DropDownList 中的选择与列出可接受值的数据库表绑定 在某个时间点 这些值为 一 二 三 四 在稍后的某个时刻 可接受的值列表将更改为 一 二 四 五 但是 数据库中存储下拉列表值的字段在某些行上仍然包含值 三 加载其中
  • 是否有正确的方法将自定义 Javascript 添加到 ASP.NET MVC 5 页面?

    目前 我已将 jQuery 源文件添加到 ASP NET 项目的 Scripts 文件夹中 在 Layout cshtml 页面中 我包含了 Scripts jquery 2 1 1 min js 现在 我可以在我制作的每个页面上包含 jQ
  • 响应不按顺序

    我正在使用 Obout com MVC 控件 并在我的视图之一中包含以下代码 Html Obout new ComboBox Languages Width 175 SelectedIndex int ViewData DefaultLan
  • 在部分视图中传递参数 - MVC3/Razor

    如何将参数传递给 MVC3 razor 中的局部视图 我在 MVC 项目中用部分视图替换了常规视图页面 对于常规视图页面 我传递了如下参数 public ActionResult MeanQ int id Access access db
  • Razor mvc3 + jquery + Url 操作 + 部分视图

    我有一个关于 jQuery Razor 的问题 我想使用 razor 和 Url Action 构建一个 javascript 变量 并且 html 属性将是输入的值 像这样 var d1 d1 val var d2 d2 val var
  • MVC3 中定义路由的文件

    我有这个文件
  • ASP.NET MVC - 临时要求除一页之外的整个站点授权的简单方法

    我正在建立一个混合了公共页面和会员专用页面的网站 登录系统按原样工作正常 不过 我想启动一个封闭的 仅限邀请的预览 并暂时要求访问者登录才能执行除欢迎页面之外的所有操作 目前我有 Authorize 某些操作方法的属性 我也可以向其他操作方
  • 为什么这条路线不匹配

    我在获取匹配路线时遇到一些问题 我使用 base 32 编码的 int 作为 Web 应用程序中幻灯片的短链接 每个幻灯片有 5 个不同的版本 我使用首字母来区分每个版本 路由始终匹配 除非 Base 32 编码 int 的第一个字符与指定
  • 使用 MVC 3 中的 Razor View 引擎从部分视图渲染部分

    我在底部主布局中渲染了一个部分 这通常是在页面渲染时在页面底部渲染 javascript 的部分 在 View 和 partial 视图中定义该部分 页面呈现时 它会从页面视图呈现部分 但不会从 partial 视图呈现部分 如何将 par
  • 提交Ajax表单后如何用消息更新_Layout.cshtml中的DIV?

    目前我有一把剃须刀View像这样 TotalPaymentsByMonthYear cshtml model MyApp Web ViewModels MyViewModel using Ajax BeginForm TotalPaymen
  • ASP.NET MVC 防伪造令牌不安全

    在没有 ssl 的情况下向服务器发出请求时 我实际上可以看到 MVC3 框架以纯文本形式生成的验证令牌密钥 该密钥存储在名为 RequestVerificationToken Lw 的 cookie 中 在混合安全环境中 实际上可以在向非
  • 如何强制控制器/操作使用 JsonValueProvider

    再会 我正在使用 ASP NET MVC 3 其中JsonValueProvider http haacked com archive 2010 04 15 sending json to an asp net mvc action met
  • EditorFor 的最小值和最大值

    我一直在尝试这段代码来设置我的最小值和最大值EditorFor
  • .net dropdownlist对齐文本

    我正在尝试将 net 下拉列表中的文本向右对齐 使用 CssClass 我可以在 Firefox 中将文本向右对齐 IE 不会将文本右对齐 而是左对齐 我读到 IE 6 不支持这个 这是真的 我使用的是 IE7 但我的大多数用户将使用 IE
  • 如何使用 jQuery 在 ASP.NET MVC 3 中设置会话变量?

    所以这就是问题 如何使用 jQuery 在 ASP NET MVC 3 中设置 Session 变量 我正在尝试使用 ajax or post但问题是我真的不知道该怎么办 描述 只需发布到控制器并在那里设置会话变量即可 Sample jQu
  • IE提示打开或保存服务器的json结果

    兼容模式下的Internet Explorer通过ajax回调方法从服务器获取数据 如果我想保存数据或打开数据 会弹出一个对话框 如何摆脱它 客户说 ajax type POST data UIdlgHolder gt form seria
  • ASP.NET MVC区域命名空间问题

    我在我的 asp net mvc 3 解决方案中创建一个名为的新区域admin Visual Studio 自动分配名称空间 MyApp areas admin controllers 我将其更改为MyApp admin controlle
  • 实体框架中的多态性

    具体类 BankAccount and CreditCard 在控制器上不可见 我被这个问题困扰了 我正在使用该网站的示例 http weblogs asp net manavi archive 2010 12 28 inheritance

随机推荐

  • 验证规则未使用 2 个验证规则正确更新

    我浏览了一些有关验证规则的帖子 但没有遇到我遇到的问题 我正在 WPF 窗口中的文本框使用验证规则 我有两项检查 一项针对空文本框 另一项针对使用正则表达式匹配的无效字符 我的问题是这样的 在我的文本框中 A 型 可以工作 不显示任何内容
  • 如何检查字符串是否是数字?

    我想用这段代码检查一个字符串是否是一个数字 我必须检查字符串中的所有字符是否都是整数 但 while 返回总是 isDigit 1 我不知道为什么 if 不起作用 char tmp 16 scanf s tmp int isDigit 0
  • mysqli 自动递增生成的主 ID

    insert INSERT INTO event tracker table event name event location location number event creator username event creator em
  • parLapply 从内部函数将数据意外复制到节点

    我有一个很大的列表 30GB 其功能如下 cl lt makeCluster 24 outfile Foo1 lt function cl largeList return parLapply cl largeList Bar Bar1 l
  • PHP parse_ini_file 对 URL 起作用吗?

    PHP方法有吗解析ini文件处理托管在云中的 INI 文件 现在 我的每一个应用程序服务器中都有一个配置文件 在任何给定时间可能有 4 8 个 手动对每台服务器进行配置更改是非常痛苦的 我已尝试以下方法但无济于事 handle fopen
  • 使用Python识别ETF持有量

    我想创建一个网络爬虫来收集 ETF 的具体持有量 我发现 Zacks com 创建了一个很好的列表 列出了我正在寻找的内容 我正在尝试使用 BeautifulSoup 但是我很难精确定位 符号 列中的数据 我需要更改或添加什么才能将所有符号
  • 在JavaFX中显示pdf [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 目前不接受答案 开发桌面应用程序JavaFX这需要显示pdf 我读到不支持 pdf 查看 显示JavaFX 当前版本 我读到JPedal too 现在 问题 是否有
  • c 读取非 ASCII 字符

    我正在解析一个包含以下字符的文件 如果我们假设我已经存储了文本文件的一行 如下所示 define MAXLINESIZE 1024 char buffer malloc MAXLINESIZE fgets buffer MAXLINESIZ
  • C++:char test[100] vs array vs string

    如果我有一个长度恒定的字符串 我应该使用什么 char test 100 std array
  • 将 DataTable 分配给 ComboBox,然后进行更改

    VB2010 我手动创建了一个数据表 因此它不是来自数据库 我已将其分配给组合框 它显示我的数据列 如果我更改数据表 是否必须重新建立链接 assign first table dt GetFirstTable cbo DataSource
  • 为什么 UIGraphicsGetCurrentContext 在 UIGraphicsBeginImageContext 之后返回 nil

    我正在按照代码示例制作模糊的 UILabel https stackoverflow com a 62224908 2226315 我的要求是在标签初始化后使标签模糊 而不是调用blur运行时的方法 但是 当我尝试打电话时blur标签初始化
  • 简单的画布动画

    我有一个简单的画布动画 两个矩形朝两个不同的方向移动 但是 我觉得这可以进一步简化 http jsfiddle net tmyie R5wx8 6 var canvas document getElementById canvas c ca
  • 如何实现Android应用的SHARE功能?

    有时我们可以看到 单击某些 共享 按钮后 会显示可共享方式的列表 该列表似乎是动态生成的 而不是硬编码的 比如我手机上安装了SpringPad 有些应用的分享功能可以通过SpringPad分享内容 但是它怎么知道我有SpringPad呢 这
  • 似乎无法从 ionic 项目生成 APK

    我是 ionic 的新手 试图获取用于调试的 apk 我在项目目录中使用了以下命令 ionic cordova platform add android 我确实得到了 platforms android 目录 然后我用了 ionic cor
  • 我可以通过 Google apps 脚本填写 TextItem 吗?

    我使用 Google Form Builder 制作了一个表单 然后为其添加了一个脚本 我可以对受访者的电子邮件地址运行 Session getEffectiveUser getEmail 但我无法将其填写在文本框中来帮助他们 我可以用 G
  • 捏合缩放以实现自定义视图

    我已经创建了自定义视图 并且想为自定义视图应用捏缩放 怎么做 Android 开发者博客上的这篇文章很好地涵盖了这个主题 向下滚动到有关手势检测器 理解多点触控 如果您只想实现捏合缩放 则只需要几行代码 private ScaleGestu
  • 使用 ienumerable 实现 ienumerable

    在泛型集合类中使用 IEnumerable Generic 接口实现 IEnumerable Non generic 需要什么 msdn 上的代码示例说明 链接 http msdn microsoft com en us library 9
  • 无法从传输连接读取数据:调用 WSACancelBlockingCall 中断了阻塞操作

    我正在开发一个客户端 服务器聊天应用程序 当我关闭客户端窗口时遇到以下异常 无法从传输连接读取数据 调用 WSACancelBlockingCall 中断了阻塞操作 知道可能是什么问题吗 如果您对底层流的任何读取器或写入器调用 Close
  • 迭代 RDD 并更新可变集合会返回空集合

    我是 Scala 和 Spark 的新手 希望得到一些帮助来理解为什么下面的代码没有产生我想要的结果 我正在比较两个表 我想要的输出模式是 case class DiscrepancyData fieldKey String fieldNa
  • Telerik MVC Grid:如何在列中使用 DropDownList?

    我有一个 Telerik MVC 网格 位于带有 Razor 的 MVC 3 应用程序中 它是 Ajax 绑定的 我现在尝试向其中添加一个下拉列表列 以便用户可以在编辑模式下使用它 但不知道如何操作 网格显示产品列表 我希望下拉列表包含可以