Telerik MVC Grid:如何在列中使用 DropDownList? [英] Telerik MVC Grid: How to use DropDownList in a column?

查看:21
本文介绍了Telerik MVC Grid:如何在列中使用 DropDownList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Telerik MVC grid, in an MVC 3 application with Razor, which is being Ajax-bound. I am now trying to add a drop list column to it, so that users can use it in edit mode, but can't figure out how. The grid displays a list of Products, and I want the drop list to contain a collection of ProductCategories, to which the Product can be associated. I've been at this for hours now and I'm out of ideas. I really hope someone here can help :)

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

I have been referencing a Telerik demo, which is located here.

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

I think the part that is hanging me up is in a help view that the demo uses. In the demo, this is called "ClientEmployee(Editor)." In my case, I've placed the helper in a file called "ProductCategoryDropList.cshtml". In this helper, I'm having a tough time getting the DropDownList to bind correctly. I think this might be because I'm not setting up the BindTo() method with the right data somehow. I've marked this point of confusion in the sample DropDownList Helper code, below, with "SomeCollectionReference," as the first parameter in a "new SelectList()" constructor call. When I try to put "Model" in that spot, I get a NullReferecne exception. When I try to access ViewBag data containing the list, I get a message similar to "the SelectList doesn't have a ProductCategoryID column," or something like that. So, I'm not sure what else to try.

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

I'm not sure how clear this description of my problem is, but in an effort to be complete, I've included the code that I think is relevant below.

控制器:

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())
                    });
}

查看:

这有点长,但我试图通过将//<--- DropList Here"放在我要处理的列旁边来简化它.

This is a bit long, but I've tried to simplify it by placing "// <--- DropList Here" next to the column that I am trying to work with.

@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>
}

型号:

[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;
        }
    }
}

DropList 助手:

@model Models.PresentationModels.ProductPresentationModel

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

ProductMapper:

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;
}

推荐答案

我向 Telerik 的优秀支持人员询问了这个问题.这是他们给我的答案:

I asked the good support folks at Telerik about this. Here is the answer they gave me:

Model 为 null 因为渲染了 DropDownList 部分视图用于ajax编辑.在这种情况下,网格会预渲染所有部分视图编辑器模板,以便它可以在客户端使用它们.在这种情况下模型将为空.如果您使用服务器绑定和编辑模型将设置为正确的值.

The Model is null because the DropDownList partial view is rendered for ajax editing. In that case the grid prerenders all partial view editor templates so it can use them on the client-side. In that case Model will be null. If you used server binding and editing the Model would be set to the right value.

此时,我将接受这篇文章作为我问题的答案.不幸的是,在这种情况下我不得不接受我自己的答案,但是......好吧,我没有其他人可以选择:)

At this point, I'm going to accept this post as the answer to my question. It's unfortunate that I have to accept my own answer in this case, but ... well, I didn't get any others to choose from :)

这篇关于Telerik MVC Grid:如何在列中使用 DropDownList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆