Thursday, 31 January 2013

Download Files From Grid in Kendo UI

View
@(Html.Kendo().Grid<MvcApplication1.Models.TestModels>()
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.ID).Groupable(false);
        columns.Bound(p => p.Name);
        columns.Template(@).ClientTemplate("Download file").Title("Download1");
        columns.Template(@).ClientTemplate("" + Html.ActionLink("Download me", "DocumentDownload2", "Home", new { id = "#=ID#" }, null) + "").Title("Download2");

    })

     .DataSource(dataSource => dataSource
          .Ajax()
          .Read(read => read.Action("Grid_Read", "Home"))
     )
)
Controller
public ActionResult Grid_Read([DataSourceRequest] DataSourceRequest request)
{
    List<TestModels> models = new List<TestModels>();

    for (int i = 1; i < 6; i++)
    {
        TestModels model = new TestModels();
        model.ID = i;
        model.Name = "Name" + i;
        models.Add(model);
    }

    return Json(models.ToDataSourceResult(request));
}


public ActionResult DocumentDownload1()
{
    string contentType = "application/xlsx";
    string filePath = Server.MapPath("~/Files/YourFileName.xlsx");
    return File(filePath, contentType, "YourFileName.xlsx");
}

public ActionResult DocumentDownload2(int id)
{
    string contentType = "application/xlsx";
    string filePath = Server.MapPath("~/Files/YourFileName.xlsx");
    return File(filePath, contentType, "YourFileName_" + id.ToString() + ".xlsx");
}

Monday, 21 January 2013

How to use special characters in enums in asp.net

aspx
<telerik:radgrid autogeneratecolumns="False" id="RadGrid1" onitemdatabound="RadGrid1_ItemDataBound" onneeddatasource="RadGrid1_NeedDataSource" runat="server">
            <mastertableview datakeynames="Rating" editmode="InPlace">
                <columns>
                    <telerik:gridboundcolumn datafield="Shipper" headertext="Shipper" uniquename="Shipper">
                    </telerik:gridboundcolumn>
                    <telerik:gridboundcolumn datafield="ShipperName" headertext="ShipperName" uniquename="ShipperName">
                    </telerik:gridboundcolumn>
                    <telerik:gridtemplatecolumn uniquename="Rating">
                        <itemtemplate>
                            <asp:label id="Label1" runat="server" text="<%# Eval(&quot;Rating&quot;) %>"></asp:label>
                        </itemtemplate>
                        <edititemtemplate>
                            <telerik:radcombobox id="RadComboBox1" runat="server">
                            </telerik:radcombobox>
                        </edititemtemplate>
                    </telerik:gridtemplatecolumn>
                    <telerik:grideditcommandcolumn>
                    </telerik:grideditcommandcolumn>
                </columns>
            </mastertableview>
</telerik:radgrid>
aspx.cs
protected void Page_Load(object sender, EventArgs e)
    {
      Class1.BindDropDownListWithEnum(ref DropDownList1, typeof(Enums.ShipperRating));
    }
    protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Shipper", typeof(int));
        dt.Columns.Add("ShipperName", typeof(string));
        dt.Columns.Add("Rating", typeof(int));
        dt.Rows.Add("1", "ShipperName1", "1");
        dt.Rows.Add("2", "ShipperName2", "2");
        dt.Rows.Add("3", "ShipperName3", "2");

        RadGrid1.DataSource = dt;
    }
    protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item.IsInEditMode && e.Item is GridEditableItem)
        {
            GridEditableItem item = e.Item as GridEditableItem;
            RadComboBox RadComboBox1 = item.FindControl("RadComboBox1") as RadComboBox;
            int Rating = Convert.ToInt32(item.GetDataKeyValue("Rating"));
            Class1.BindRadComboBoxWithEnum(ref RadComboBox1, typeof(Enums.ShipperRating));

            if (RadComboBox1.Items.FindItemByValue(Convert.ToString(Rating)) != null)
            {
                RadComboBox1.Items.FindItemByValue(Convert.ToString(Rating)).Selected = true;
            }
        }
    }
Class1.cs
public class DisplayValue : Attribute
{
    private string _value;

   
    public DisplayValue(string value)
    {
        _value = value;
    }

    public string Value
    {
        get { return _value; }
    }
}

public class EnumListItem
{
    private int _value;
    public int Value
    {
        get { return this._value; }
        set { this._value = value; }
    }

    private string _displayName;
    public string DisplayName
    {
        get { return _displayName; }
        set { _displayName = value; }
    }

    private string _name;
    public string Name
    {
        get { return _name.Replace("_", " "); }
        set { _name = value.Replace("_", " "); }
    }

    public EnumListItem(int Value, string Name, string DisplayName)
    {
        _value = Value;
        _displayName = string.IsNullOrEmpty(DisplayName) ? Name : DisplayName;
        _name = Name;
    }
}


public class Enums
{

    public enum ShipperRating
    {
        [DisplayValue("1-3 (Poor)")]
        Poor = 1,
        [DisplayValue("4-5 (Fair/Average)")]
        Average = 2,
        [DisplayValue("6-7 (Good)")]
        Good = 3

    }
}

public static class Class1
{
    public static void BindDropDownListWithEnum(ref DropDownList ddl, Type enumType)
    {
        List<enumlistitem> el = GetEnumValues(enumType, false);
        ddl.DataSource = el;
        ddl.DataTextField = "DisplayName";
        ddl.DataValueField = "Value";
        ddl.DataBind();
    }

    public static void BindRadComboBoxWithEnum(ref RadComboBox radcmb, Type enumType)
    {
        List<enumlistitem> el = GetEnumValues(enumType, true);
        radcmb.DataSource = el;
        radcmb.DataTextField = "DisplayName";
        radcmb.DataValueField = "Value";
        radcmb.DataBind();
    }
    public static List<enumlistitem> GetEnumValues(Type type, bool isSelectRequired)
    {
        List<enumlistitem> el = new List<enumlistitem>();
        EnumListItem ei;
        foreach (int item in Enum.GetValues(type))
        {
            ei = GetEnumItem(type, item);
            el.Add(ei);
        }
        if (isSelectRequired)
        {
            el.Insert(0, new EnumListItem(0, "--Select--", "--Select--"));
        }
        return el;
    }
    public static EnumListItem GetEnumItem(Type type, int item)
    {
        string name = Enum.GetName(type, item);
        string displayName = string.Empty;
        object[] displayAttributes = type.GetField(Enum.GetName(type, item)).GetCustomAttributes(typeof(DisplayValue), false);
        if (displayAttributes.Length > 0)
            displayName = ((DisplayValue)displayAttributes[0]).Value;
        else
            displayName = name.Replace("_", " ");

        
        return new EnumListItem(item, name, displayName);
    }
}

Wednesday, 16 January 2013

Set column editable mode based on another column value changes in kendo UI

View
@(Html.Kendo().Grid<MvcApplication1.Models.TestModels>()
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.ID);
            columns.Bound(p => p.Name);
            columns.Bound(p => p.IsActive);
            columns.ForeignKey(p => p.FID, (System.Collections.IEnumerable)ViewData["TestList"], "Value", "Text");

        })
        .ToolBar(toolBar => toolBar.Save())
        .Editable(editable => editable.Mode(GridEditMode.InCell))
        .Pageable()
        .Sortable()
        .Scrollable()
        .Filterable()
        .Events(e => e.Edit("onGridEdit"))
        .DataSource(dataSource => dataSource
            .Ajax()
            .Batch(true)
            .ServerOperation(false)
            .Events(events => events.Error("errorHandler"))
            .Model(model =>
            {
                model.Id(p => p.ID);
                model.Field(p => p.ID).Editable(false);
            })
        .Read(read => read.Action("ForeignKeyColumn_Read", "Home"))
        .Update(update => update.Action("ForeignKeyColumn_Update", "Home"))
        )
    )
Controller
namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {

            List<SelectListItem> items = new List<SelectListItem>();

            for (int i = 1; i < 6; i++)
            {
                SelectListItem item = new SelectListItem();
                item.Text = "text" + i.ToString();
                item.Value = i.ToString();
                items.Add(item);
            }

            ViewData["TestList"] = items;

            return View();
        }

        public ActionResult ForeignKeyColumn_Read([DataSourceRequest] DataSourceRequest request)
        {
            List<TestModels> models = new List<TestModels>();

            for (int i = 1; i < 6; i++)
            {
                TestModels model = new TestModels();
                model.ID = i;
                model.Name = "Name" + i;
                
                if (i % 2 == 0)
                {
                    model.IsActive = true;
                    model.FID = i;
                }

                models.Add(model);
            }

            return Json(models.ToDataSourceResult(request));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ForeignKeyColumn_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<TestModels> tests)
        {
            if (tests != null && ModelState.IsValid)
            {
                // Save/Update logic comes here
            }

            return Json(ModelState.ToDataSourceResult());
        }
    }
} 
Model
namespace MvcApplication1.Models
{
    public class TestModels
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public bool IsActive { get; set; }
        public int FID { get; set; }
    }
}
JS
<script type="text/javascript">

    function errorHandler(e) {
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            alert(message);
        }
    }

    function onGridEdit(arg) {
        if (arg.container.find("input[name=IsActive]").length > 0) {
            arg.container.find("input[name=IsActive]").click(function () {
                if ($(this).is(":checked") == false) {
                    arg.container.next().html("");
                    arg.model.FID = "0";
                }
                else {
                    arg.model.IsActive = true;
                    $("#Grid").data("kendoGrid").closeCell(arg.container);
                    $("#Grid").data("kendoGrid").editCell(arg.container.next());
                }
            });
        }
        if (arg.container.find("input[name=FID]").length > 0) {
            if (arg.model.IsActive == false) {
                $("#Grid").data("kendoGrid").closeCell(arg.container)
            }
        }
    }
</script>

DOWNLOAD DEMO