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

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

问题描述

我有一个Telerik的MVC网格,与剃刀,正在阿贾克斯绑定一个MVC 3应用程序。现在我想一个下拉列表列添加到它,这样用户就可以在编辑模式下使用它,但无法弄清楚如何。网格显示产品的清单,我想下拉列表包含ProductCategories的集合,以使产品能有关。我已经在这几个小时,现在,我的想法。我真的希望这里有人能帮助:)

我一直在引用Telerik的演示,它位于这里

我认为这是挂了我的一部分,该演示使用帮助视图。在演示中,这被称为ClientEmployee(编辑)。就我而言,我已经放在帮手一个名为ProductCategoryDropList.cshtml的文件。在这个帮手,我有一个艰难的时间让DropDownList的正确结合。我想这可能是因为我没有设置不知怎么用正确的数据BindTo()方法。我标志着样本DropDownList的助手code这点困惑,下面,以SomeCollectionReference,作为一个新的SelectList()构造函数调用的第一个参数。当我尝试在该位置把模型,我得到一个NullReferecne例外。当我试图访问包含列表ViewBag数据,我得到类似选择列表没有ProductCategoryID列,或类似的东西的消息。所以,我不知道还有什么尝试。

我不知道我的问题的描述多么明确的是,但在努力完成,我已经包括了code,我认为是以下相关的。

控制器:

 公众的ActionResult指数()
{
    ViewBag.ProductCategories =新的SelectList(_productCategoryService.GetActiveProductCategories(),ProductCategoryID,ProductcategoryName);
    变种产品= _productService.GetProducts()了ToList()。
    VAR presentationModel = _mapper.MapAsList(产品);
    返回查看(presentationModel);
}//
// GET:/产品/
[GridAction]
公众的ViewResult _index()
{
    ViewBag.ProductCategories =新的SelectList(_productCategoryService.GetActiveProductCategories(),ProductCategoryID,ProductcategoryName);
    返回查看(新GridModel<产品presentationModel>
                    {
                        数据= _mapper.MapAsList(_productService.GetProducts()了ToList())
                    });
}

查看:

这是有点长,但我已经尝试通过将简化为//< --- DropList这里的旁边,我想一起工作列

  @model IEnumerable的<模式presentationModels.Product presentationModel>@(Html.Telerik()网格(模型).HtmlAttributes(新{风格=宽度:100%;})
        //给网格中的HTML id属性值
        。名称(ProductGrid)
        //树立promiry键,用于插入,更新和删除命令
        .DataKeys(dataKeys => dataKeys.Add(P => p.ProductID))
        //添加一个Insert命令网格工具栏
        .ToolBar(命令=方式> commands.Insert()按钮类型(GridButtonType.ImageAndText))
        //使用Ajax数据绑定将数据绑定到网格
        .DataBinding(数据绑定= GT;数据绑定
                //阿贾克斯绑定
                阿贾克斯()
                    。选择(_指数,产品)
                    // Home.Insert插入新的数据记录
                    .Insert(创建,产品)
                    // Home.Update更新现有数据记录
                    .Update(编辑,产品)
                    // Home.Delete删除现有的数据记录
                    .Delete(删除,产品)
        )
        .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(?<输入类型=复选框禁用=禁用NAME ='主动'<#= ProductActive检查=​​'检查':''#> />中);
            columns.Bound(p值=> p.ProductCategoryName); //< --- DropList这里
            columns.Command(命令=>
            {
                。commands.Edit()按钮类型(GridButtonType.Image);
                。commands.Delete()按钮类型(GridButtonType.Image);
            });
        })
        .Editable(编辑= GT; editing.Mode(GridEditMode.PopUp))
        .ClientEvents(事件=> events.OnEdit(onEdit))
        .Pageable()
        .Scrollable()
        .Sortable()
        .Filterable()
)@section HeadContent {
    <脚本类型=文/ JavaScript的>
        功能onEdit(五){
            $(e.form).find('#ProductCategoryName')。数据(tDropDownList')。选择(功能(DataItem的){
                返回dataItem.Text == e.dataItem ['ProductCategoryName'];
            });
        }
    < / SCRIPT>
}

型号:

  [显示名称(@类别名称)]
[UIHint(ProductCategoryDropList),要求]
[StringLength(255,的ErrorMessage = @产品类别名称不能为长度超过255个字符)]
公共字符串ProductCategoryName
{
    得到
    {
        字符串名称=的String.Empty;        如果(_model.ProductCategory!= NULL)
        {
            名称= _model.ProductCategory.ProductCategoryName;
        }        返回名称;
    }
    组
    {
        如果(_model.ProductCategory!= NULL)
        {
            _model.ProductCategory.ProductCategoryName =价值;
        }
    }
}

DropList助手:

  @model模型。$ ​​P $ psentationModels.Product presentationModel@(Html.Telerik()。DropDownList的()
        。名称(ProductCategoryName)
            .BindTo(新的SelectList(小于SomeCollectionReference>中ProductCategoryID,ProductCategoryName))

ProductMapper:

 公开名单<产品presentationModel> MapAsList(列表<产品与GT;产品)
{
    //变种所属分类=新的SelectList(_productCategoryService.GetProductCategories()了ToList(),ProductCategoryID,ProductCategoryName);    VAR presentationModels =产品
            。选择(X =>新建商品presentationModel()
            {
                的ProductID = x.ProductID,
                ProductCategoryID =(!?(x.ProductCategory = NULL)x.ProductCategory.ProductCategoryID:0)
                ProductCategoryName =((x.ProductCategory = NULL)x.ProductCategory.ProductCategoryName!?的String.Empty)
                产品名称= x.ProductName,
                产品描述= x.ProductDescription,
                PricePerMonth = x.PricePerMonth,
                ProductImagePath = x.ProductImagePath,
                ProductActive = x.ProductActive,
                ProductCategories =新的SelectList(_productCategoryService.GetProductCategories()。了ToList(),ProductCategoryID,ProductCategoryName)//所属分类
            })了ToList()。    返回presentationModels;
}


解决方案

我在问Telerik的这个良好的支持人员。这是他们给我的答案是:


  

由于DropDownList的局部视图呈现的模型是空
  阿贾克斯编辑。在这种情况下,网格prerenders所有局部视图
  编辑模板,以便它可以在客户端使用它们。在这种情况下
  型号为null。如果您使用的服务器绑定和编辑模式
  将被设置为正确的值。


在这一点上,我会接受这个职位的回答我的问题。这是不幸的,我必须要接受我自己的答案在这种情况下,但是......好吧,我没有得到任何其他可供选择:)

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 :)

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

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.

Controller:

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:

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

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

DropList Helper:

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

解决方案

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

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网格:如何在列中使用的DropDownList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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