Telerik Forums
UI for ASP.NET Core Forum
1 answer
64 views

I was tasked at my company with implementing custom parameter editors in order to dynamically hide parameter depending on whether they should be available for use or not. I first followed this tutorial to create the custom parameter editors and the corresponding HTML5 Widget. Once I did that, I tried integrating the custom parameter edtiors into a HMTL5 Report Viewer using the ASP.NET Core 8 tutorial (links here, here, here) but after building both the REST service project and the HTML5 viewer, whenever I run the app, I simply land on a blank localhost page leading to Microsoft Tutorials on building NET Core apps. I have tried all available troubleshooting & looked at documentation but I have no idea how to move forward. I have double checked that I followed the tutorials correctly and still no progress. I am using Telerik Report Desginer R3 2020, Visual Studio 2022, .Net 8. Attached below is the code for the program.cs, appsettings.json, reportscontroller.cs, and index.html


AppSettings.json (Rest Project)

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
        "Telerik.Reporting.Examples.CSharp.Properties.Settings.TelerikConnectionString": "Data Source =.\\SQLEXPRESS; Initial Catalog=AdventureWorks; Intgrated Security = true"
    }
    
}

 



namespace TopLevelStatements.Controllers
{
    using System.Net;
    using System.Net.Mail;
    using Microsoft.AspNetCore.Mvc;
    using Telerik.Reporting.Services;
    using Telerik.Reporting.Services.AspNetCore;

    [Route("api/[controller]")]
    [ApiController]
    public class ReportsController : ReportsControllerBase
    {
        public ReportsController(IReportServiceConfiguration reportServiceConfiguration)
        : base(reportServiceConfiguration)
        {
        }

        protected override HttpStatusCode SendMailMessage(MailMessage mailMessage)
        {
            throw new System.NotImplementedException("This method should be implemented in order to send mail messages");

            // using (var smtpClient = new SmtpClient("smtp01.mycompany.com", 25))
            // {
            //     smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            //     smtpClient.EnableSsl = false;
            //     smtpClient.Send(mailMessage);
            // }
            // return HttpStatusCode.OK;
        }
    }
}


using Microsoft.Extensions.DependencyInjection.Extensions;
using Telerik.Reporting.Services;
using Telerik.Reporting.Cache.File;


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddControllers().AddNewtonsoftJson();

// Configure dependencies for ReportsController.
builder.Services.TryAddSingleton<IReportServiceConfiguration>(sp =>
    new ReportServiceConfiguration
    {
        // The default ReportingEngineConfiguration will be initialized from appsettings.json or appsettings.{EnvironmentName}.json:
        ReportingEngineConfiguration = sp.GetService<IConfiguration>(),
        // In case the ReportingEngineConfiguration needs to be loaded from a specific configuration file, use the approach below:
        //ReportingEngineConfiguration = ResolveSpecificReportingConfiguration(sp.GetService<IWebHostEnvironment>()),
        HostAppId = "ReportingNet6",
        Storage = new FileStorage(),
        ReportSourceResolver = new UriReportSourceResolver(System.IO.Path.Combine(sp.GetService<IWebHostEnvironment>().ContentRootPath, "Reports"))
    });

builder.Services.AddCors(corsOption => corsOption.AddPolicy(
    "ReportingRestPolicy",
    corsBuilder =>
    {
        corsBuilder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader();
    }
));


var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapControllers();
    //...
});

app.UseStaticFiles();

app.UseAuthorization();

app.MapRazorPages();

app.UseCors("ReportingRestPolicy");

app.Run();


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Telerik HTML5 Report Viewer Demo in ASP.NET Core in .NET 5</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale-1, maximum-scale=1" />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <link href="https://kendo.cdn.telerik.com/2020.3.1118/styles/kendo.common.min.css" rel="stylesheet" />
    <link href="https://kendo.cdn.telerik.com/2020.3.1118/styles/kendo.blueopal.min.css" rel="stylesheet" />
    <script src="https://localhost:44320/api/reports/resources/is/telerikReportViewer"></script>
    <style>
        #reportViewer1 {
            position: absolute;
            left: 5px;
            right: 5px;
            top: 50px;
            bottom: 5px;
            overflow: hidden;
            font-family: verdana, Arial;
    </style>
</head>
<body>
    <div id="reportViewer1">
        loading...
    </div>
    <script>
        $(document).ready(function () {
            $("#reportViewer1")
                .telerik_ReportViewer({
                    serviceurl: "https://localhost:44320/api/reports/", reportSource: {
                    },
                    report: "Barcodes Report.trdp", parameters: {}
viewMode: telerikReportViewer.ViewModes.INTERACTIVE, scaleMode: telerikReportViewer.ScaleModes.SPECIFIC, scale: 1.0,
                    enableAccessibility: false,
                    sendEmail: enabled: true }
});
});</script>
</body>
</html>

Dimitar
Telerik team
 answered on 21 Aug 2024
1 answer
77 views

I've tried

$("#lockAspectRatio").data('kendoCheckBox').value(false);

and while it does uncheck the box, the aspect ratio is still locked in the background. Seems like there's a trigger/event that's firing when someone manually checks/unchecks the box and that event does not get fired when the check is set programmatically.

How do I programmatically "uncheck" the lockAspectRatio checkbox in the ImageEditor Crop toolbar?

Ivaylo
Telerik team
 answered on 20 Aug 2024
0 answers
35 views

Hello,

Im using angular 16 and .net core 7 version. When i send request to back-end, i can handle. But i have a problem.

Let's assume we have two tables: roles and users. In Angular, there's a grid where I display the roles. I'm having issues on the backend side when applying filtering in that grid.

 <kendo-grid-column [width]="300" title="Rol" [sortable]="cantFilterandSort" field="Roles">
            <ng-template kendoGridFilterCellTemplate let-filter let-column="column">
                <kendo-multiselect [checkboxes]="true" [autoClose]="false" [tagMapper]="tagMapper"
                    [data]="this.roleList" textField="name" valueField="idx"
                    [valuePrimitive]="true"  (valueChange)="onRoleFilterChange($event)"></kendo-multiselect>
            </ng-template>
        </kendo-grid-column>

onRoleFilterChange(selectedRoles: any[]): void {
    this.state.filter = {
      logic: 'and',
      filters: selectedRoles.map(role => ({
          field: 'Roles',
          operator: 'eq',
          value: role
      }))
  };
    this.getAllData();
  }

The request is reaching the back-end.

[HttpPost]
public async Task<IActionResult> GetAllUser([DataSourceRequest] DataSourceRequest filter)
{
    var result = await this.userService.GetAllUser(filter);
    return CreateActionResultInstance(result);
}


public async Task<DataSourceResult> GetAllUser(DataSourceRequest filter)
{

    var result = await entity
          .AsNoTracking()
          .IgnoreQueryFilters()
          .Include(y => y.Roles)
          .Select(x => new UserViewModel
          {
              Idx = x.Idx,
              Email = x.Email,
              Name = x.Name,
              Phone = x.Phone,
              Surname = x.Surname,
              UserName = x.UserName,
              Roles = x.Roles.Select(x => x.Idx)
          }).ToDataSourceResultAsync(filter);
    return result;}

What I need here is for the filtering to work when a role is selected as a filter in the user list on the screen. How can we use a many-to-many table in this case? I researched a lot but couldn't find anything online.

As a note, the IDs of the roles are of type GUID.

Thanks :)



Ingenico
Top achievements
Rank 1
 asked on 20 Aug 2024
1 answer
139 views

I added a content security policy and wanted to remove unsafe-inline so I'm deferring components globally.

@Html.Kendo().DeferredScripts()

The problem is that I have other JavaScript code which references components in the jQuery document ready function which now don't work. I think  it's because the components haven't been initialized yet.

When deferring components globally how do you execute JavaScript code after the components have been initialized?

Thank you

Tsvetomila
Telerik team
 answered on 16 Aug 2024
1 answer
64 views
I have a grid for EditOrderLineDto which has a child element of EditOrderLineProductDto:

public class EditOrderLineDto
{
    public long Id { get; set; }
    public long OrderId { get; set; }
    public int Quantity { get; set; }

    public EditOrderLineProductDto Product { get; set; }

    public EditOrderLineDto()
    {
        Product = new EditOrderLineProductDto();
    }

    public EditOrderLineDto(long id, long orderId, string productId, string productName,
         int quantity)
    {
        Id = id;
        OrderId = orderId;
        Quantity = quantity;
        Product = new EditOrderLineProductDto(productId, productName);
    }
}

public class EditOrderLineProductDto
{
    public string ProductId { get; set; }
    public string Name { get; set; }

    public EditOrderLineProductDto()
    {
        ProductId = string.Empty;
        Name = string.Empty;
    }

    public EditOrderLineProductDto(string productId, string name)
    {
        ProductId = productId;
        Name = name;
    }
}

I would like the grid to display the data from the child element in separate columns while being able to edit all of these values through an editor for EditOrderLineProductDto. Is this possible?
Current grid setup is below.
Html.Kendo().Grid<EditOrderLineDto>()
    .Name("orderLines")
    .ToolBar(t =>
    {
        t.Create();
        t.Save();
    })
    .Columns(c =>
    {
        c.Bound(x => x.Id).Hidden(true);
        c.Bound(x => x.OrderId).Hidden(true);
        c.Group(g =>
            g.Title("Product").Columns(p =>
            {
                p.Bound(x => x.Product.Name);
                p.Bound(x => x.Product.ProductId);
            })
        );
        c.Bound(x => x.Quantity);

        c.Command(x => x.Edit());
        c.Command(x => x.Destroy());
    })
    .Editable(x => x.Mode(GridEditMode.InLine))
    .DataSource(d =>
    {
        d.Ajax()
        .Batch(false)
        .Model(m =>
        {
            m.Id(x => x.Id);
            m.Field(x => x.Id).DefaultValue(0);
            m.Field(x => x.OrderId).DefaultValue(Model.Id);
            m.Field(x => x.Product).DefaultValue(new EditOrderLineProductDto()).Editable(true);
            m.Field(x => x.Quantity);
        })
        .Create(c => c.Action("CreateOrderLine", "Orders"))
        .Read(r => r.Action("EditOrderOrderLines", "Orders", new { orderId = Model.Id }))
        .Update(u => u.Action("EditOrderLine", "Orders"))
        .Destroy(d => d.Action("DestroyOrderLine", "Orders"))
        .Events(e => e.Error("onError"));
    })
    .Events(e => e.Save("onGridSave"))


Ivaylo
Telerik team
 answered on 16 Aug 2024
1 answer
44 views

Hi, 

I have been trying to implement the multiSelect with no avail. 

I have been trying to implement the multiselect and although in the pop up is working, meaning I am able to see the possible values as well as I am able to select the values, when I press save. The model that is used to create the whole object contains null instead of the selected values.

When I check in the WebApp the payload the MultiSelect looks like this:

ActivitiesUuids[0].Disabled: false

ActivitiesUuids[0].Group:

ActivitiesUuids[0].Selected: false

ActivitiesUuids[0].Text: name of the activity (I have changed the name for security)

ActivitiesUuids[0].Value: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (I have changed the Guid number into x, the value is actually a proper Guid)

 

My Models:

    public class CourseContentViewModel
    {public List<Guid>? RelatedCourseContensUuids { get; set; }  //contains a list of values that has been/should be chosen from the multiselec}

    public class CombinedCourseContentViewModel
    {public SelectList RelatedCourseContens { get; set; }  //contains a list of the values that multiSelect has to choose from}

 

Controller:

This is inside the Index and List methods.

           ICollection<CourseContentResponseDTO> responseDTOs = await _akdService.CourseContentsAllAsync();

           combinedCourseContentViewModel.RelatedCourseContentViewModel = new SelectList(responseDTOs, "Uuid", "Name");

 

Grid implementation:

@(Html.Kendo().Grid<WebApp.Models.CourseContentViewModel>().Name("grid")
    .Columns(columns =>
    {
        columns.Bound(n => n.Name).Filterable(false).Title("Username").Width(250);
        columns.Command(command => { command.Edit().Text("Edit"); command.Destroy().Text("Delete"); }).Width(200);
    })
    .ToolBar(toolBar =>
    {
        toolBar.Create().Text("Create");
    })
    .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("CourseContentCreateUpdate"))
    .Pageable()
    .Sortable()
    .Scrollable()
    .Filterable()
    .DataSource(dataSource => dataSource
    .Ajax()
    .PageSize(30)
    .Model(model =>
    {
        model.Id(p => p.Uuid);
    })
    .Read(read => read.Action("List", "CourseContent"))
    .Update("Update", "CourseContent")
    .Create(create => create.Action("Create", "CourseContent"))
    .Destroy(destroy => destroy.Action("Delete", "CourseContent"))
    )
    )


This is my pop-up template multiselect (other components likes comboBoxes are working fine):

            <label class="Headings">Related Course Content</label>
            <kendo-multiselect for="RelatedCourseContensUuids"
                               name="RelatedCourseContensUuids"
                               datatextfield="Text"
                               datavaluefield="Value"
                               placeholder="No items selected..."
                               bind-to="combinedCourseContentViewModel.RelatedCourseContentViewModel">
            </kendo-multiselect>

My implementation of comboBoxes is almost the same except difference in naming of the tag helpers.

Hope you can help! 

Juste

Ivaylo
Telerik team
 answered on 15 Aug 2024
1 answer
90 views

Hello,

I have this code on my index.cshtml:

@(Html.Kendo().MultiSelect()
    .Name("selectedmembers")
    .Placeholder("Please select the members on the job...")
    .DownArrow(true)
    .AutoClose(false)
    .DataTextField("MemberName")
    .DataValueField("MemberId")
    .Filter("contains")
    .DataSource(source =>
    {
        source.Read(read =>
        {
            read.Action("GetPeople", "Combo");
        });
    })
    )

And my GetPeople code looks like this:

public JsonResult GetPeople(string text)
{
    using (var db = new chilternModel())
    {
        var members = db.Members.Select(member => new Member()
        {
            MemberName = member.MemberName,
            MemberId = member.MemberId
        });

        return Json(members.ToList());
    }
}

When I run the code I get undefined as the text value.  The database is a mySql running locally.

I have checked the members variable and it has the appropriate information for a jsonResult to be returned, but the control seems to ignore the text field (and I assume the MemberId as well)

Thanks in advance.

Michael

Ivaylo
Telerik team
 answered on 12 Aug 2024
2 answers
76 views

Hello,

I am trying to build a grid that has a combobox in it that should be filled from an Ajax request. But based on the demo on the page, I am not being able to determine where the combobox is filled.

I appreciate any help on the matter.

Regards,

Alexandre

Alexandre
Top achievements
Rank 2
Iron
Iron
Iron
 answered on 08 Aug 2024
1 answer
168 views

Currently we are using Telerik ASP.NET Core 2024.2.514 and in MVC HtmlHelper methods such as Kendo().DatePickerFor() do not support properties of C# type DateOnly.

Is this supported in a version later than we are using or is if not is it on project plans for future inclusion?

Same applies for TimeOnly.

Mihaela
Telerik team
 answered on 08 Aug 2024
1 answer
97 views

In 2024.1 and 2024.2 (perhaps other versions, but those are the two I tried), using ToDataSourceResult to filter on a property whose type is DateOnly results in an InvalidCastException.  This is due to ToDataSourceResult using .NET's Convert.DefaultToType which does not support converting to DateOnly.  Per https://github.com/dotnet/runtime/issues/73074 (which is about a different but related method), the team at Microsoft is adamant about not adding the support because the Convert methods have fallen out of vogue.  As a workaround, I wrote a method to scan through the filter tree of the DataSourceRequest and pre-convert any value corresponding to a DateOnly property from a string or DateTime to a DateOnly so that it will not need to be converted within ToDataSourceResult, but that is quite tedious since I have to do that to each of my applications and call it before every call to ToDataSourceResult.  It would be nice if ToDataSourceResult could handle this case internally.

 

For reference, here is the relevant part of the stack trace:

at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
   at Kendo.Mvc.Infrastructure.Implementation.Expressions.FilterDescriptorExpressionBuilder.CreateValueExpression(Type targetType, Object value, CultureInfo culture)
   at Kendo.Mvc.Infrastructure.Implementation.Expressions.FilterDescriptorExpressionBuilder.CreateBodyExpression()
   at Kendo.Mvc.FilterDescriptor.CreateFilterExpression(ParameterExpression parameterExpression)
   at Kendo.Mvc.FilterDescriptorBase.CreateFilterExpression(Expression instance)
   at Kendo.Mvc.Infrastructure.Implementation.Expressions.FilterDescriptorCollectionExpressionBuilder.CreateBodyExpression()
   at Kendo.Mvc.CompositeFilterDescriptor.CreateFilterExpression(ParameterExpression parameterExpression)
   at Kendo.Mvc.FilterDescriptorBase.CreateFilterExpression(Expression instance)
   at Kendo.Mvc.Infrastructure.Implementation.Expressions.FilterDescriptorCollectionExpressionBuilder.CreateBodyExpression()
   at Kendo.Mvc.Infrastructure.Implementation.Expressions.FilterExpressionBuilder.CreateFilterExpression()
   at Kendo.Mvc.Extensions.QueryableExtensions.Where(IQueryable source, IEnumerable`1 filterDescriptors)
   at Kendo.Mvc.Extensions.QueryableExtensions.CreateDataSourceResult[TModel,TResult](IQueryable queryable, DataSourceRequest request, ModelStateDictionary modelState, Func`2 selector)
   at Kendo.Mvc.Extensions.QueryableExtensions.ToDataSourceResult(IQueryable queryable, DataSourceRequest request, ModelStateDictionary modelState)
   at Kendo.Mvc.Extensions.QueryableExtensions.ToDataSourceResult(IQueryable queryable, DataSourceRequest request)

Mihaela
Telerik team
 answered on 08 Aug 2024
Narrow your results
Selected tags
Tags
+? more
Top users last month
Anislav
Top achievements
Rank 6
Silver
Bronze
Bronze
Jianxian
Top achievements
Rank 1
Iron
Marco
Top achievements
Rank 3
Iron
Iron
Iron
Jim
Top achievements
Rank 2
Iron
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Anislav
Top achievements
Rank 6
Silver
Bronze
Bronze
Jianxian
Top achievements
Rank 1
Iron
Marco
Top achievements
Rank 3
Iron
Iron
Iron
Jim
Top achievements
Rank 2
Iron
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?