This is a migrated thread and some comments may be shown as answers.

[Solved] Dropdownlist in a Helper Method

2 Answers 147 Views
ComboBox
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Naveen
Top achievements
Rank 1
Naveen asked on 03 Jan 2012, 12:27 PM
Hi,

I need to put the common things that we do to generate a telerik dropdown in a helper method. The helper method will be generating the list items in the same method instead of using viewbag, tempdata or anything of that sort.

But I'm not able to get any of the Telerik controls in the helper methods. Please suggest on how to implement or is there any work around to do this.

Thanks in advance.

2 Answers, 1 is accepted

Sort by
0
Accepted
John DeVight
Top achievements
Rank 1
answered on 13 Jan 2012, 10:26 PM

Hi Naveen,

One approach would be to extend the Telerik DropDownList to have a new method that would populate the DropDownList and render it.  For example, if you want to have an extension method to render a DropDownList of colors, you could do the following:

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using SampleApplication.Data;
using SampleApplication.Models;
  
namespace Telerik.Web.Mvc.UI
{
    using Fluent;
  
    public static class CustomDropDownListExtensions
    {
        public static void RenderColors(this DropDownListBuilder dropDownListBuilder)
        {
            IList<Color> colors = SampleRepository.GetColors();
            dropDownListBuilder.BindTo(new SelectList(colors, "Id", "Name"));
            dropDownListBuilder.Render();
        }
    }
}

In the view, you could then do this:

@{
    Html.Telerik().DropDownList().Name("dropdownlist").RenderColors();
}

The Color class would look like this:

namespace SampleApplication.Models
{
    public class Color
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

and the ColorRepository class would look like this:

namespace SampleApplication.Data
{
    using Models;
  
    public class SampleRepository
    {
        public static IList<Color> GetColors()
        {
            IList<Color> colors = new List<Color>();
            colors.Add(new Color { Id = 1, Name = "Brown" });
            colors.Add(new Color { Id = 2, Name = "Black" });
            colors.Add(new Color { Id = 3, Name = "Red" });
            return colors;
        }
    }
}

Let me know whether this is what you wanted.  If not, we can come up with something that does.

Regards,

John DeVight
0
Naveen
Top achievements
Rank 1
answered on 16 Jan 2012, 08:14 AM
Though I was looking at Html Helper methods initially this is not a bad option at all.

Thanks a ton.
Tags
ComboBox
Asked by
Naveen
Top achievements
Rank 1
Answers by
John DeVight
Top achievements
Rank 1
Naveen
Top achievements
Rank 1
Share this question
or