Telerik Forums
UI for ASP.NET AJAX Forum
2 answers
51 views

Hi, I'm using a ClientDataSource with a Grid to communicate with a webservice from client-side.

The webservice returns a custom response for any request: {"ErrorMessage":(error message or null),"IsSuccessful":(boolean),"Result":[(result of request)]}.

In the ClientDataSource I defined the schema as follows to check for server errors

<Schema DataName="Result" ResponseType="JSON" ErrorsName="ErrorMessage">
  <Model ID="id">
  </Model>
</Schema>

And this function to show the error:

function dataSource_error(e) {
   e.preventDefault();
   console.log("Error", e);
   serverNotification.set_title("Server Error");
   serverNotification.set_text(e.errors);
   serverNotification.update();
   serverNotification.show();
 }

My problem is that when I try to remove an item from the clientdatasource and I get a custom error,the item is still removed from the clientdatasource and the grid which is not an effect I'm looking for.

For the clientdatasource remove/destroy I'm using a function:

dataSource.transport.destroy = function (options) {
   console.log("Options-destroy", options);
   console.log(dataSource);
   $.ajax({
      url: ("<%= WebApp.WebServiceHelper.BASE_WS_URL + WebApp.WebServiceHelper.WS_CLOSE %>"),
      dataType: "json",
      data: {
         username: sessionStorage["username"],
      },
      success: function (result) {
        console.log("result-destroy:", result);
                        //if (result.IsSuccessful) {
        options.success(result);
                        //} else {
                        //    options.error(result);
                        //}
        console.log("Options-destroy-success", options);
        console.log(dataSource);
      },
      error: function (result) {
        console.log("result1-destroy:", result);
        options.error(result);
      }
   });
};

Before adding ErrorsName in the schema I was check the IsSuccessful on success and call options.error, in this case the clientDataSource remove the item but the grid did not rebind !

On the same topic is it possible to check if IsSuccessful is false instead of ErrorMessage is null to generate an error and get the error message from ErrorMessage?

In case of remove, the Result will be a boolean, can I also prevent the clientDataSource from removing an element if if Result is false?

 

Marin
Telerik team
 answered on 30 Nov 2016
0 answers
89 views

I am adding a default initial filter from the code-behind, but I'm getting an error:
System.Web.Query.Dynamic.ParseException

 

  • MyGrid :
<telerik:RadGrid    ID="RG_Lst_CS" runat="server" DataSourceID="LDS_SuiviCommande"
             OnPreRender="RG_Lst_CS_PreRender" EnableLinqExpressions="true"
             EnableHeaderContextFilterMenu="True" EnableHeaderContextMenu="True"
             AllowFilteringByColumn="True" AllowPaging="True" AllowSorting="True" >
 
<MasterTableView AutoGenerateColumns="False" >
   <Columns>
      <telerik:GridDateTimeColumn DataField="CCE_DateReception" HeaderText="Date Reception"
                         SortExpression="CCE_DateReception"
                         UniqueName="CCE_DateReception"
                         EnableTimeIndependentFiltering="true"
                         DataType="System.DateTime" DataFormatString="{0:d}" />
   </Columns>   
</MasterTableView>
</telerik:RadGrid>

  • Code behind :
protected void RG_Lst_CS_PreRender(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
    var DefaultDateInterval =  DateTime.Today.AddDays(
          (DayOfWeek.Monday - DateTime.Today.DayOfWeek) - 14);
    RG_Lst_CS.MasterTableView.FilterExpression =
          "([CCE_DateReception] >= DateTime.Parse(\"" + DefaultDateInterval + "\")) ";
    GridColumn column = RG_Lst_CS.MasterTableView.GetColumnSafe("CCE_DateReception");
    column.CurrentFilterFunction = GridKnownFunction.GreaterThanOrEqualTo;
    column.CurrentFilterValue = DefaultDateInterval.ToString();
    RG_Lst_CS.Rebind();
   }
}

"([CCE_DateReception]>=DateTime.Parse(\""+DefaultDateInterval+"\")) "
Is based on Current filter expression when i use the Build-in grid filter.
But I also try:
"([CCE_DateReception] >= \"" + DefaultDateInterval + "\" ) "


The Error occure on RG_Lst_CS.Rebind() or RG_Lst_CS.MasterTableView.Rebind()
And EnableLinqExpressions="true" do not look to do the trick.


Pierre
Top achievements
Rank 1
 asked on 30 Nov 2016
1 answer
357 views

Hi 

I use RadWizard and create 10 WizardStep, each step content 10 textbox and 10 Custom Validation.

I use client function to validate these textbox, like below , the code will help me to find which textbox are repeated.

My question is when step 2 textbox value and step 1 textbox value repeated, the validator fired. I wish each step just only have it validator, each step will not interference each other. How Can I do ?

  <script type="text/javascript">
        function validateTxt(sender, args) {
            var txts = new Array();
            args.IsValid = true;
            txts = document.getElementsByTagName('input')  
            var valus = new Array();
            for (i = 0; i < txts.length; i++) {  
                if (txts[i].type == 'text') { 
                    if (isNaN(txts[i].value)) {
                        args.IsValid = false;
                        break;
                    } else {  
                        for (j = 0; j < valus.length ; j++) {
                            if (valus[j] == txts[i].value.trim()) {  
                                args.IsValid = false;
                                break;
                            }
                        }
                        if (txts[i].value.trim() != '') {   
                            valus[valus.length] = txts[i].value.trim();
                        }
                    }
                }
                if (args.IsValid == false) {
                    break;
                }
            }
        }
    </script>

 

part of server side code 

        protected void Page_Load(object sender, EventArgs e)
        {
           
            NumberOfGroup = tas.Get_Group_Emp("7", "1").Rows.Count;
            QuestionNumber = tas.Get_Question_By_Group("1", "1", "7").Rows.Count;
            Question = tas.Get_Question_By_Group("1", "1", "7");
            //重點是,每一個 RadWizardStep 要有自己的 ValidationGroup Name,WizardStep 底下的元素的 Validation Group 名稱要與上層相同
            if (!Page.IsPostBack)
            {

                RadWizard wizard = new RadWizard() { ID = "Wizard1", Skin = "Sunset" ,EnableAjaxSkinRendering=true, RenderMode=RenderMode.Mobile };
                
                wizard.Culture = new System.Globalization.CultureInfo("zh-TW");
                wizard.Localization.Next = "下一題";
                wizard.Localization.Previous = "上一題";
                wizard.Localization.Finish = "完成";
                wizard.WizardStepCreated += RadWizard1_WizardStepCreated;
                wizard.FinishButtonClick += Wizard_FinishButtonClick;

                RadWizardStep startStep = new RadWizardStep() { ID = "startStep", StepType = RadWizardStepType.Start, Title="評量開始" };
                string term1 = "正向思考且有生產力的員工能讓公司充滿幹勁。<br/>個人、團隊及經理的定期績效評估 – 可讓您及時瞭解公司主幹健全與否。<br/> 由人力資源部 進行的員工調查問卷,可讓管理階層蒐集提升業務最需要的意見反應。<br/> 焦點員工評核可讓管理階層及其工作小組,展開關於職涯發展與目標的深度對話。<br/>";
                startStep.Controls.Add(new Literal() { Text = "<div id='term1' class='EULA'>"+term1+"</div>" });
                wizard.WizardSteps.Add(startStep);
                // 依據 QuestionNumber 來決定迴圈大小,一個步驟一題
                for (int i = 0; i < QuestionNumber; i++)
                {
                    //這邊長題目
                    RadWizardStep step = new RadWizardStep() { ID = "step" + (i + 1).ToString(), Title = "問題" + (i + 1).ToString(), ToolTip = "問題" + (i + 1).ToString(), CausesValidation = true, ValidationGroup = "group" + (i + 1).ToString(), StepType = RadWizardStepType.Step };
                    step.Controls.Add(new Literal() { Text = "<div id='question' style='margin:0 auto;font-family: 'cwTeXFangSong', serif;'>" });
                    step.Controls.Add(QuestionLabel=new RadLabel() { });
                    step.Controls.Add(new Literal() { Text = "</div>" });
                    //這邊長照片 依據 Group 人數
                   
                        step.Controls.Add(new Literal() { Text = "<div style='margin:0 auto; position: relative; width: 950px ;text-align:center;border:1px solid red;'>" });

                        for (int j = 0; j < NumberOfGroup; j++)
                        {
                            step.Controls.Add(new Literal() { Text= "<div class='HeadPicture'>" });
                            RadBinaryImage image = new RadBinaryImage() { ID = "RadImage" + (i + 1).ToString() + (j + 1).ToString(), ImageUrl = "/img/2_"+(j+1).ToString()+".png", CssClass = "ImageCSS" , ToolTip="Your Name..User "+(j+1).ToString()};
                            step.Controls.Add(image);

                            //TextBox textbox = new TextBox() { ID = "TextBox" + (i + 1).ToString() + (j + 1).ToString(), ValidationGroup = "group" + (i + 1).ToString(), CssClass = "TextBoxCSS" };
                            //step.Controls.Add(textbox);
                            RadNumericTextBox RadNumbericText = new RadNumericTextBox() { ID = "RadNumericText" + (i + 1).ToString() + (j + 1).ToString(), ValidationGroup = "group" + (i + 1).ToString(), ShowSpinButtons = true, ButtonsPosition = InputButtonsPosition.Left, MaxValue = NumberOfGroup, MinValue = 1, Type = NumericType.Number, CssClass = "TextBoxCSS", RenderMode = RenderMode.Classic };
                            RadNumbericText.NumberFormat.DecimalDigits = 0;
                            RadNumbericText.IncrementSettings.InterceptArrowKeys = true;
                            RadNumbericText.IncrementSettings.InterceptMouseWheel = true;
                            RadNumbericText.IncrementSettings.Step = 1;
                            RadNumbericText.ForeColor = System.Drawing.Color.DarkGreen;
                            RadNumbericText.Font.Bold = true;
                            step.Controls.Add(RadNumbericText);

                            //RequiredFieldValidator ReqValidator = new RequiredFieldValidator() { ID = "validator" + (i + 1).ToString() + (j + 1).ToString(), ValidationGroup = "group" + (i + 1).ToString(), ControlToValidate = RadNumbericText.ID, ErrorMessage = "*", ForeColor = System.Drawing.Color.Red, EnableClientScript = true };
                            //step.Controls.Add(ReqValidator);

                              CustomValidator cValidator = new CustomValidator() { ID = "cValidator" + (i + 1).ToString() + (j + 1).ToString(), ValidationGroup = "group" + (i + 1).ToString(), ClientValidationFunction = "validateTxt",Display=ValidatorDisplay.Dynamic, ErrorMessage = "*", ValidateEmptyText = true, ForeColor = System.Drawing.Color.BlueViolet, EnableClientScript = true };
                            //  ValidationSummary vSummary = new ValidationSummary() { ID = "vSummary" + (i + 1).ToString()+(j+1).ToString(), ValidationGroup = "group" + (i + 1).ToString(), ShowMessageBox = true, DisplayMode = ValidationSummaryDisplayMode.List };
                              step.Controls.Add(cValidator);
                            //  step.Controls.Add(vSummary);
                            //    //剩下換頁換步驟時,CustomValidator 必須重新綁定的問題,不然前後頁的值會互相比對,只希望比單頁的就好


                            step.Controls.Add(new Literal() { Text="</div>" });
                        }
                        step.Controls.Add(new Literal() { Text = "</div></br>" });
                    wizard.Controls.Add(step);
                }

                RadWizardStep finalStep = new RadWizardStep() { ID = "finalStep", StepType = RadWizardStepType.Finish, Title="評量結束" };
                string term2 = "謝謝你的參與";
                finalStep.Controls.Add(new Literal() { Text = "<div id='term1' class='EULA'>" + term2 + "</div>" });
                wizard.WizardSteps.Add(finalStep);
                this.Form.Controls.Add(wizard);
            }
        }

        private void Wizard_ActiveStepChanged(object sender, EventArgs e)
        {
            
        }

        private void Wizard_FinishButtonClick(object sender, WizardEventArgs e)
        {
            // 關閉瀏覽器...
            Response.Write("<script language='javascript'>window.open('', '_self', ''); window.close();</script>");
        }

        protected void RadWizard1_WizardStepCreated(object sender, WizardStepCreatedEventArgs e)
        {
            // 這裡載入題目
            if (!(e.RadWizardStep.ID == "startStep" || e.RadWizardStep.ID == "finalStep"))
            {
                //RadLabel QuestionLabel = new RadLabel();
                QuestionLabel.Text = Question.Rows[Convert.ToInt32(e.RadWizardStep.Index-1)]["Question"].ToString() + "(1 ~ " + NumberOfGroup +" 分)";
                QuestionLabel.CssClass = "LabelFont";
            }
        }

 

 

Dimitar
Telerik team
 answered on 30 Nov 2016
3 answers
1.8K+ views

I have a button inside RadAjaxPanel and i want to export it to the Excel Sheet, Below is the code i had written to do this task. If i removed the RadAjaxpanel then i can export the datatable into excel sheet. But when trying to export  it to Excel using radajax panel, I'm getting this error: Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed."

<telerik:RadAjaxPanel ID="mainPanel" runat="server" LoadingPanelID="RadAjaxLoadingPanel">
        <table class="reportSearch">
            <tr>
                <td>
                    <telerik:RadButton ID="btnExcelDetail" runat="server" Text="Excel" OnClick="btnExcelDetail_Click" ValidationGroup="SearchValidation" ClientEvents-OnRequestStart="requestStart">
                            <Icon PrimaryIconUrl="~/App_Themes/RnDThemes/images/insert_table_on.gif" PrimaryIconHeight="15" />
                        </telerik:RadButton>
                </td>
                <td>
                </table>
</telerik:RadAjaxPanel>
<script type="text/javascript">
function requestStart(sender, args) {               
                if (args.get_eventTarget().indexOf("btnExcelDetail") >= 0)
                    args.set_enableAjax(false);
            }
</script>
public void ExporttoExcel(DataTable table, string filename)
    {
        try
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + "");
            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
            HttpContext.Current.Response.Write("<TABLE border='1' bgColor='#ffffff' " +
              "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
              "style='font-size:10.0pt;background:white;'><TR>");
            int columnscount = table.Columns.Count;
            for (int j = 0; j < columnscount; j++)
            {
                HttpContext.Current.Response.Write(@"<TD><B>" + table.Columns[j].ToString() + "</B></TD>");
            }
            HttpContext.Current.Response.Write("</TR>");
            foreach (DataRow row in table.Rows)
            {
                HttpContext.Current.Response.Write("<TR>");
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    if (row[i].ToString().Trim().Length > 1 && row[i].ToString().Trim().StartsWith("0") && row[i].GetType().Name=="String")
                        HttpContext.Current.Response.Write("<TD style=\"mso-number-format:\\@\">");
                    else
                        HttpContext.Current.Response.Write("<TD>");
                    HttpContext.Current.Response.Write(row[i].ToString());
                    HttpContext.Current.Response.Write("</TD>");
                }
                HttpContext.Current.Response.Write("</TR>");
            }
            HttpContext.Current.Response.Write("</TABLE>");
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.SuppressContent = true;
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }       
        catch (Exception) { }
Viktor Tachev
Telerik team
 answered on 30 Nov 2016
0 answers
187 views

Hi, everyone,

As far as I know, RadEditor doesn't have a page break functionality when HTML is exporting to DOCX. I've found a solution for this:

 

DocxFormatProvider provider = new DocxFormatProvider();
HtmlFormatProvider htmlProvider = new HtmlFormatProvider();

List<string> result = this.PrepareStringToExport(htmlPage); //result is a list with divided "pages"
RadFlowDocument newDoc = new RadFlowDocument();
RadFlowDocumentEditor newEditor = new RadFlowDocumentEditor(newDoc);
RadFlowDocument document;
foreach(string element in result)
{
document = new RadFlowDocument();
document = htmlProvider.Import(element);
newEditor.InsertDocument(document);
newEditor.InsertBreak(BreakType.PageBreak);
}
byte[] byteArray = provider.Export(newEditor.Document);
string fileName = "filename.docx";
Utils.SendBytesAsFileToClientWithAjax(Response, fileName, byteArray);

 

If there is a cleaner solution, let me know

 

Best regards

Marcin

Marcin
Top achievements
Rank 1
 asked on 30 Nov 2016
7 answers
272 views

Hello,

I have an OrgChart and a couple of labels and an image that I want to export to PDF using the RadClientExportManager.
Code .aspx: 

table id="exporttopdf">
    <tr>
        <td>
 
            <asp:image runat="server" imageurl="~/styles/images/logo.png" />
            <asp:panel runat="server" id="Panel1" visible="false">
                            <span class="content">
                                GRUPP: <asp:Label runat="server" ID="Label1"></asp:Label><br />
                                DATUM: <asp:Label runat="server" ID="Label2"></asp:Label>
                            </span>
                        </asp:panel>
        </td>
    </tr>
    <tr>
        <td>
            <telerik:RadOrgChart ID="RadOrgChart2" runat="server" GroupColumnCount="1" DisableDefaultImage="true">
                <GroupEnabledBinding>
                    <NodeBindingSettings DataFieldID="ID" DataFieldParentID="ParentID" />
                    <GroupItemBindingSettings DataFieldNodeID="NodeID" DataFieldID="ID" DataTextField="Text" />
                </GroupEnabledBinding>
            </telerik:RadOrgChart>
        </td>
    </tr>
</table>

However my swedish special characters doesn't show properly in the PDF.
I've been using this demo http://docs.telerik.com/devtools/aspnet-ajax/controls/clientexportmanager/how-to/exporting-special-characters
and it works as expected.

What do I need to do to get it to work with the orgChart?

Any suggestions appreciated

Regards

Janne

Veselin Tsvetanov
Telerik team
 answered on 30 Nov 2016
19 answers
1.1K+ views
Please help me how to add a row in Header and merge some cells in row of Header

RJ
Top achievements
Rank 1
 answered on 30 Nov 2016
5 answers
679 views
I've a rad grid and I want to set the focus on a specified row of the grid using javascript.

I've done this function:


     function setActiveRow(p) {
         var grid = $find("<%=RadGridDati.ClientID%>");
         var masterTableView = grid.get_masterTableView();
         masterTableView.get_dataItems()[p].get_element().cells[0].focus();
     }

where p is the row number I want to set the focus.
It's running correctly with Explorer but not with Firefox and Crome.
Some ideas?

Thanks in advan ce
Eyup
Telerik team
 answered on 30 Nov 2016
2 answers
74 views

I noticed that the markers on the map looks mispositioned on many devices, like shifted to north/east.

I got this problem with my Android phone and even with a Surface pro, whatever the browser I 'm using.

You can see it even with the online demo:
http://demos.telerik.com/aspnet-ajax/map/examples/overview/defaultcs.aspx

On PC:
https://i.snag.gy/IzuexH.jpg

On my phone:
https://i.snag.gy/XTwYrK.jpg

I think it's just a css issue with the markers. I really need a quick solution to the problem. Any ideas? :/

zaza
Top achievements
Rank 1
 answered on 29 Nov 2016
1 answer
1.1K+ views

Hi Team,

I have a Radgrid which has DateTime Column with enable range filter. I am using AllowCustomPaging="True" And I am displaying the date as "24/11/2016 15:31:15" and I want that when I choose from date and To date the filter expression should format the filter date.

For example From date is "23/11/2016" and To Date is "24/11/2016" then it should change to "20161123" and "20161124" before passing to database.

Could you please help me on this.

~

Sandeep

Vasil
Telerik team
 answered on 29 Nov 2016
Narrow your results
Selected tags
Tags
+? more
Top users last month
Bohdan
Top achievements
Rank 3
Iron
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Elliot
Top achievements
Rank 1
Iron
Iron
Iron
Sunil
Top achievements
Rank 1
Cynthia
Top achievements
Rank 1
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Bohdan
Top achievements
Rank 3
Iron
Iron
Iron
Rob
Top achievements
Rank 3
Bronze
Bronze
Iron
Elliot
Top achievements
Rank 1
Iron
Iron
Iron
Sunil
Top achievements
Rank 1
Cynthia
Top achievements
Rank 1
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?