Tuesday, June 19, 2012

Grid Row Html Attributes & Row Color in Telerik MVC Grid

There are two ways of get this done in Telerik MVC Grid component.

If you are using server side binding, I think it is a little handy in several cases. You can add this in your aspx page to Grid component:


        .RowAction(row =>
        {
            if (row.DataItem.GridKey == 2012)
            {
                row.HtmlAttributes["style"] = "background:red;";
            }
        })


You can custumize as you wish the string assigned to HtmlAttributes["style"] element. It will work the style element in a html tag.


If you are using Ajax binding that means you have to do the style thing in OnRowDataBound event. It has to be in javascript and sometimes you may not able to access your control attributes. Here is the code:



          .ClientEvents(events => events.OnRowDataBound("Grid_OnRowDataBound"))


         <script type="text/javascript">
          function Grid_OnRowDataBound(e) {
             if (e.dataItem.GridKey == 2012) {
                e.row.style.backgroundColor = "red";
             }
          }
          </script>



We have added the style attribute for each row seperately at OnRowDataBound event. You can add anything like font-size, bold or not, italic, etc.

If there is any mistakes let me know, so I can fix :)


Regards,
Mehmet.

Tuesday, June 12, 2012

Posting Xml to URL with Credentials

Posting an XML to an given URL make me search google over 3 hours but at last I managed to solve the problems and successfully posted my xml.

There are some tricks like length of content, encoding of stream writer, Flush method should be called, etc. Each will be mentioned seperately.

First of all we make a web request to start a post and we will get a web response in return.
Here are our variables,


            System.Net.WebRequest req = null;
            System.Net.WebResponse rsp = null;


You can put the code in a try catch since you will get some undesired responses when you first try. We define the uri and then give it to webrequest as parameter.


            req = System.Net.WebRequest.Create(uri);


We should provide credentials if the uri that we define will request username and password.


            req.Credentials = new NetworkCredential(Username, Password);


Then we define method and  content type of web request,


            req.Method = "POST";
            req.ContentType = "text/xml";


We should set our content length to the length of xml variable which is a string in our case. If you just use the length attribute of string then request will not be able to match the content length and actual length of xml and you will get the exception,

            Bytes to be written to the stream exceed the Content-Length bytes size specified.

We should get the length with an encoding as follows,


            req.ContentLength = System.Text.Encoding.UTF8.GetByteCount(xml);


After defining the length with an encoding, Stream Writer should have the same encoding too.


            StreamWriter sw = new StreamWriter(req.GetRequestStream(), new UTF8Encoding(false));
         
Then we call write method. Until we call flush no data actually will be written to stream and without calling flush, if you close the writer you will get the error,

            Webexception: The Request was aborted: The request was cancelled.

We should use the following order,

             sw.Write(xml);
             sw .Flush();
             sw .Close();

At the end we get response and you can check which type of response is returned.

            rsp = req.GetResponse();


Above code lets you post an xml file via web request to a destination Url.

Hope it helps.
P.S : If there is any typing or coding mistakes let me know. See you later.


Thursday, June 7, 2012

How to Open a Telerik MVC Window Element in Javascipt?

Telerik Window can be managed from javascript function easily. You can check possible function names and descriptions here.

There are different ways to open a window in javascript but important one is to open as centered. Lets assume that we created a window via javascript.


    var windowElement = $.telerik.window.create({
        title: "...",
        html: "<p>I'm a window...</p>"
        contentUrl: "",
        actions: ["Maximize", "Close"],
        modal: true,
        width: 500,
        height: 500,
        resizable: false,
        draggable: true,
        scrollable: false,
        onClose: function () { }
    });

You can open it by just the following line :

    windowElement.center().open();

This will open the window but not centered surprisingly. You will have to get .data element first and then call the open and center functions.

    var window = $(windowElement).data('tWindow');
    window.center().open();


Above code will allow you successfully open a centered window.


Hope it helps.
P.S : If there is any typing or coding mistakes let me know. See you later.

Telerik MVC Grid Detail Popup with Partial View (3)

This post is just an update to my previous post where partial view with Telerik Window is described. We will update just two steps and the rest will be the same but I will post all details including updated parts.

First we need a column command button in our grid.

        .Columns(columns =>
        {
            //Columns here
            columns.Command(commands =>
            {
                //Other commands
                commands.Custom("viewDetails").ButtonType(GridButtonType.Text)
                             .Text("Detail");
            }).Width(60);
        })

This time we need a different event instead of OnRowSelect.

       .ClientEvents(events =>  events.OnRowDataBound("OnRowDataBound"))

Then we need two javascript functions in script tags. First one will handle the OnRowDataBound event, and second one will handle OnClick event of our custom command button. Id is grid's routevalue, and we use custom command's id to locate our element, t-grid-viewDetails.

        function OnRowDataBound(e) {
            var id = e.dataItem.Id;
            $(e.row).find('a.t-grid-viewDetails').attr('href', 'javascript:ViewDetails_OnClick(' + id + ');');
        }

In the older version of this approach, we put window as invisible in the aspx page and then opened it in javascript function. Here, we will create window in the javascipt function and then open it.
As we create window in javascript, we no longer need hardcoded window in the aspx page, you can remove it. 

        function ViewDetails_OnClick(id) {            
            $.ajax({
                type: 'POST',
                url: '<%= Url.Action("Action", "Controller") %>',
                data: { Id:  id },
                dataType: 'html',
                success: function (htmlData) {
                    var windowElement = $.telerik.window.create({
                        title: "...",
                        html: htmlData,
                        contentUrl: "",
                        actions: ["Maximize", "Close"],
                        modal: true,
                        width: 500,
                        height: 500,
                        resizable: false,
                        draggable: true,
                        scrollable: false,
                        onClose: function () {
                             $("#popupWindow").data('tWindow').destroy();
                         }
                     });
                    windowElement.attr('id', 'popupWindow');
                    var window = $(windowElement).data('tWindow');
                    window.center().open();

                }
            })
        }

And at last, our action method did not change.

        public ActionResult Action(int Id)
        {
            //Prepare model for PartialView
            return PartialView("PartialViewName", model);
        }     

Above code pops up a detail window with your partial view when custom command is clicked.

Hope it helps.
P.S : If there is any typing or coding mistakes let me know. See you later.

How to add custom templates in Telerik MVC Dropdownlist/Combobox control?

In Telerik MVC application you can use either Ajax or Server binding for populating comboboxes. Here I did it via Ajax binding but you can do similar thing for Server binding also.

In our controller class we need a method which will return Json object after Ajax call. Telerik combobox/dropdownlist does support html tags inside its text value so we use this feature and replace text column with image tags we fill.


        [HttpPost]
        public ActionResult _AjaxFillCombo()
        {
            //Populate list with your object
            List<OurObject> list =  OurObjectService.GetAll();


            //Customize a column in the list
            foreach ( OurObject obj in  list  )
            {
                obj.ImageLink = //Add custom <img /> tag in here with required fields as src attribute.
            }
           
            return new JsonResult
            {
                //Return list as SelectList, set ImageLink as text attribute.
                Data = new SelectList(list.ToList(), "Id", "ImageLink")
            };
        }


Image tag can be as following,

      <img class='...' style='...' title='...' alt='...' src = '" + obj.imageLocation + "' />

After that we need to tell combobox/dropdownlist that binding will be via Ajax binding,

      .DataBinding(binding => binding.Ajax().Select(" _AjaxFillCombo ", "ControllerName"))


Hope it helps.
P.S : If there is any typing or coding mistakes let me know. See you later.

Wednesday, June 6, 2012

Telerik MVC Grid Detail Popup with Partial View (2)

Like my previous post, I will try to show another way to obtain detail view with partial view and popup. This time we will change button's href attribute and there will be no need for row selection.

First we need a column command button in our grid.



        .Columns(columns =>
        {
            //Columns here
            columns.Command(commands =>
            {
                //Other commands
                commands.Custom("viewDetails").ButtonType(GridButtonType.Text)
                             .Text("Detail");
            }).Width(60);
        })


This time we need a different event instead of OnRowSelect.


       .ClientEvents(events =>  events.OnRowDataBound("OnRowDataBound"))


As in the previous post, we have the same window.


<% Html.Telerik().Window()
        .Name("Window")
        .Modal(true)
        .Width(500)
        .Height(500)
        .Title("Window Detay")
        .Scrollable(true)
        .Draggable(true)
        .Resizable()
        .Visible(false)
        .Render(); 
    %>


Then we need two javascript functions in script tags. First one will handle the OnRowDataBound event, and second one will handle OnClick event of our custom command button. Id is grid's routevalue, and we use custom command's id to locate our element, t-grid-viewDetails.


        function OnRowDataBound(e) {
            var id = e.dataItem.Id;
            $(e.row).find('a.t-grid-viewDetails').attr('href', 'javascript:ViewDetails_OnClick(' + id + ');');
        }




        function ViewDetails_OnClick(id) {            
            $.ajax({
                type: 'POST',
                url: '<%= Url.Action("Action", "Controller") %>',
                data: { Id:  id },
                dataType: 'html',
                success: function (htmlData) {
                    $('#Window ').data('tWindow').content(htmlData);
                    $('#Window ').data('tWindow').center().open();
                }
            })
        }

And at last, our action method did not changed.


        public ActionResult Action(int Id)
        {
            //Prepare model for PartialView
            return PartialView("PartialViewName", model);
        }

       

Above code pops up a detail window with your partial view when custom command is clicked.

Hope it helps.
P.S : If there is any typing or coding mistakes let me know. See you later.





Telerik MVC Grid Detail Popup with Partial View

An easy way to achieve a popup detail window in GridView has to be the following solution (at least the easiest way I manage to find) :

First in the grid we set two properties (you may have set them already):

  •  .ClientEvents(events => events.OnRowSelect("OnRowSelect"))


  • .Selectable(selecting => selecting.Enabled(true))
Secondly we need a window to put our partial view in it. This part can be done in many ways but the trivial one is just put a telerik window on the same page with gridview.

<% Html.Telerik().Window()
        .Name("Window")
        .Modal(true)
        .Width(500)
        .Height(500)
        .Title("Window Title")
        .Scrollable(true)
        .Draggable(true)
        .Resizable()
        .Visible(false)
        .Render(); 
    %>

Later we need the javascript function OnRowSelect, either in a script tag or in a js file.
The Id field in the dataItem represents your routeValue which is set in the gridview. ActionName and ControllerName represents your action which returns PartialView.

         function OnRowSelect(e) {
            var dataItem = $('#GridName').data('tGrid').dataItem(e.row);
            var Id= dataItem['Id'];

            $.ajax({
                type: 'POST',
                url: '<%= Url.Action("ActionName", "ControllerName") %>',
                data: { id: Id},
                dataType: 'html',
                success: function (htmlData) {
                    $('# Window ').data('tWindow').content(htmlData);
                    $('# Window ').data('tWindow').center().open();
                }
            })
        }

As the final part we need the action class which responds our ajax post.

        public ActionResult ActionName(int id)
        {
            //Build model for partial view
            return PartialView("PartialViewName", model);
        }

Above code enables row selection and on row click a detail window pops up with your partial view in it.

Hope it helps.
P.S : If there is any typing or coding mistakes let me know. See you later.