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

I have

	<div class="row mt-3">
		<div class="col-lg-4">
			@(Html.Kendo().DropDownListFor(m => m.AwardTypeId)
			      .Size(ComponentSize.Medium)
			      .Rounded(Rounded.Medium)
			      .FillMode(FillMode.Outline)
			      .OptionLabel("Select Award Type...")
			      .HtmlAttributes(new { style = "width: 100%" })
			      .DataTextField("Name")
			      .DataValueField("Id")
			      .DataSource(source =>
			      {
				      source.Read(read =>
				      {
					      read.Action("GetLookupAwardTypes", "Api");
				      });
			      })
			      .Events(e =>
			      {
					e.Select("AwardTypeId_OnSelect");
			      })
				)
		</div>

		<div class="col-lg-8">
			<kendo-textbox for="TenderNumber" size="ComponentSize.Medium" rounded="Rounded.Medium" fill-mode="FillMode.Outline" enable="false">
				<textbox-label content="@nameof(Model.TenderNumber)" floating="true"/>
			</kendo-textbox>
		</div>
	</div>

Renders:

<div class="row mt-3">
		<div class="col-lg-4">
			<span title="" class="k-picker k-dropdownlist k-picker-outline k-picker-md k-rounded-md" unselectable="on" role="combobox" aria-expanded="false" tabindex="0" aria-controls="AwardTypeId_listbox" aria-disabled="false" aria-readonly="false" style="width: 100%;" aria-busy="false" aria-describedby="d51a34cd-9a61-4c07-af6f-dd41980be3a7" aria-activedescendant="c66cf112-868e-4f3d-bcfa-ad32c0cf3f7e"><span id="d51a34cd-9a61-4c07-af6f-dd41980be3a7" unselectable="on" class="k-input-inner"><span class="k-input-value-text">Tender</span></span><button type="button" tabindex="-1" unselectable="on" class="k-input-button k-button k-button-md k-button-outline k-button-outline-base k-icon-button" aria-label="select"><span class="k-icon k-i-arrow-s k-button-icon"></span></button><input data-val="true" data-val-required="The AwardTypeId field is required." id="AwardTypeId" name="AwardTypeId" style="width: 100%; display: none;" type="text" value="0" data-role="dropdownlist"></span><script>kendo.syncReady(function(){jQuery("#AwardTypeId").kendoDropDownList({"select":AwardTypeId_OnSelect,"dataTextField":"Name","dataValueField":"Id","optionLabel":"Select Award Type...","value":"0","size":"medium","rounded":"medium","fillMode":"outline","dataSource":{"transport":{"read":{"url":"/Api/GetLookupAwardTypes"},"prefix":""},"schema":{"errors":"Errors"}}});});</script>
		</div>

		<div class="col-lg-8">
			<span data-role="floatinglabel" class="k-floating-label-container k-state-empty k-focus"><label class="k-label k-input-label" for="TenderNumber">TenderNumber</label><span class="k-input k-textbox k-input-outline k-input-md k-rounded-md" style=""><input id="TenderNumber" name="TenderNumber" type="text" value="" data-role="textbox" aria-disabled="false" class="k-input-inner" autocomplete="off" style="width: 100%;"></span></span>
				
			<script>kendo.syncReady(function(){jQuery("#TenderNumber").kendoTextBox({"enable":false,"label":{"content":"TenderNumber","floating":true},"size":"medium","rounded":"medium","fillMode":"outline"});});</script>
		</div>
	</div>

That looks like this:And floating label:

How to align them properly? I'm using the Material Main theme.

Mihaela
Telerik team
 answered on 24 Aug 2022
1 answer
404 views

Hello,

I have followed various examples and my very minimal knowledge of Kendo to attempt to filter a large dataset on the server side Razor Pages Page. 

I have used this: https://docs.telerik.com/aspnet-core/html-helpers/editors/multiselect/binding/razor-page

However, I cannot get the filtered data to return correctly without type arguments being thrown by the method.

Things I have checked

  1. Pascal Case is being returned despite getting a Splice error.
  2. An empty array is being returned on from the server as a default

Code

1. MultiSelect Component

@model Guid

@(Html.Kendo().MultiSelectFor(x => x)
    .DataTextField("OrderNumber")
    .DataValueField("Id")
    .Placeholder("Start typing order numbers...")
    .Filter(FilterType.Contains)
    .DataSource(dataSource =>
    {
        dataSource.Ajax();
        dataSource.Read(r => r.Url("/XXXX/XXXX/Index?handler=OrderMultiSelectRead")
            .Data("forgeryToken")
            .Type(HttpVerbs.Post))
            .ServerFiltering(true);
    }
    ).HtmlAttributes(new {style ="width: 100%" }))

2. Server Side Code

public async Task<IActionResult> OnPostOrderMultiSelectRead([DataSourceRequest] DataSourceRequest request, string text)
        {
            var result = new List<Order>();
            try
            {

                var filters = request?.Filters?.Cast<FilterDescriptor>().ToList();

                var firstFilter = filters.FirstOrDefault();

                if (firstFilter == null) return new JsonResult(await result.ToDataSourceResultAsync(request));
                
                firstFilter.MemberType = typeof(int?);

                var firstFilterValue = firstFilter.Value.ToString();

                if (string.IsNullOrEmpty(firstFilterValue) || firstFilterValue.Length < 5)
                    return new JsonResult(await result.ToDataSourceResultAsync(request));

                var orderNumberParsedAsInt = int.Parse(firstFilterValue);

                var matchingOrders =
                    (await this.orderRepository.GetModelsAsync(x => x.OrderNumber == orderNumberParsedAsInt))
                    .OrderByDescending(x => x.OrderNumber).ToList();

                return new JsonResult(await matchingOrders.ToDataSourceResultAsync(request));
            }
            catch(Exception exception)
            {
                var resultPayload = await result.ToDataSourceResultAsync(request);

                resultPayload.Errors = new List<Exception> { exception };

                return new JsonResult(resultPayload);
            }
        }
Really struggling with this!
Momchil
Telerik team
 answered on 24 Aug 2022
1 answer
93 views

The model uses inheritance.How to make that when loading the data from the model is automatically substituted?


@(Html.Kendo().DropDownList()
                    .Name("LoginViewModels.Country.Obl")
                    .HtmlAttributes(new { style = "width:100%" })
                    .OptionLabel("Выберите область")
                    .DataTextField("Key")
                    .DataValueField("Key")
                    .DataSource(source =>
                    {
                        source.Read(read =>
                        {
                            read.Action("LoadObl", "Account");
                        });
                    })
                )

Alexander
Telerik team
 answered on 24 Aug 2022
1 answer
146 views

My grid only shows a few columns of my model.   My model is much larger than what I show on the grid.

I wanted to have a toolbar "Add new contact"  on the grid. 

In the grid rows I was going to have an "Edit Contact" button.

Both of these would pop up the same editor template.   The editor template needs to be responsive and not in a small window..   Planning for a UI four column row on deskstop but stacked on mobile.

I cannot seem to find the right example for doing this.

Help please!

Thanks

Stoyan
Telerik team
 answered on 24 Aug 2022
1 answer
1.2K+ views

I have a serious problem (with code, that is)...

I have a page with a TabStrip control on it.  Using the Selected option on the first tab (set to true) I can't get that tab to be the active tab when the page loads.  After load, clicking on any tab but the first one makes the tab LOOK like it is selected, but the content doesn't change for any tab until I click on that first tab.  In other words, I can't set the active tab using the HTML Helper - with or without the Selected property being set, the tabstrip just doesn't work until I click the first tab.

What I'm trying to do is this: tab 1 has a data grid and tabs 2-4 have charts.  When initially loaded, the grid is displayed.  When one of the other tabs are selected I want to capture that and check the number of categories in the chart.  If there are more than the current window size can handle, I want to manually set the width property of the chart and call the resize method so the user scrolls horizontally (without doing this, there are some charts where the category names look like an ink blot - one in particular can have 387 categories - ick, but what the client wants).

At this point I am not even sure if this will work.  But I know the client will pitch a fit if I can't get that first tab automatically selected when the page loads.  The next fit comes when I can't get the chart resized so it is readable.  FYI, Bootstrap 5's native tabs work but the Kendo TabStrip does not.  If I can't get this working, I will have to go back to that approach to see if I can get the chart to resize.

And FYI, this particular page is not wrapped in any Bootstrap containers, just nested in an Accordian control.

Mihaela
Telerik team
 answered on 22 Aug 2022
3 answers
651 views

Dear All.

I have a listview within the listview items are displayed. This is my current code for the html. 

<section>
       <script type="text/x-kendo-tmpl" id="templateRC">
 
            <div id="selectedRC" class=" SetHeight">
                <span>#:ID#</span>
            </div>
        </script>
 
 
        <div class="demo-section k-content wide">
            @(Html.Kendo().ListView<SLM.Models.ViewModel>()
            .Name("listView")
            .TagName("div")
            .ClientTemplateId("templateRC")                         
            .DataSource(dataSource => dataSource
            .Ajax()
            .Read(read => read.Action("_Reports_Chart", "Home", new { iTypeID = Model.TYPE2_ID })
            )                           
            )
            .Selectable(ListViewSelectionMode.Single)
            //  .Events(events => events.Change("onSelectReport"))
            )
        </div>
    </section>

My css Code:

.SetHeight {
 
    width: calc(50% - 3%);
    border: 1px solid #008000;
    margin: 1%;
    float: left;
}

When I check my browser the items will displayed like rectangles, so theyre not equal width and height. I tried adding some javascript to get the width and use it for the height but it keeps displaying like a rectangle.

The Jquery: 

$(function () {
    var divWidth = $('.SetHeight').width();
    $('.SetHeight').height(divWidth);
    console.log(divWidth);
});

 

(logging also returns null. When I create a custom project on codepen. it does work for some reason.)

So now is my question: What do I need to change/add/remove to make the boxes equal width and height(squares).

Kind regards. Bjorn

Stoyan
Telerik team
 answered on 19 Aug 2022
1 answer
169 views

I was converting HtmlHelps to TagHelpers because the formatting in my code files is getting out of control. I realized that some Kendo controls are not that straightforward to convert.

This works fine:

@(Html.Kendo().TabStrip()
      .Name("tabStrip1")
      .SelectedIndex(0)
      .Animation(animation => animation.Open(open => open.Fade(FadeDirection.In)))
      .Items(items =>
      {
	      items.Add().SpriteCssClasses("fa-duotone fa-clock-rotate-left").Text("History").Content(@<text>@Html.DisplayFor(m => m.History, "LetterHistory")</text>);
	      items.Add().SpriteCssClasses("fa-duotone fa-thumbs-up").Text("Approvers").Content(@<text>@Html.DisplayFor(m => m.Approvers, "LetterApprovers")</text>);
	      items.Add().SpriteCssClasses("fa-duotone fa-magnifying-glass").Text("Details").Content("");
		  items.Add().SpriteCssClasses("fa-duotone fa-link").Text("Attachments").Content(@<text>@await Component.InvokeAsync(viewName, new { LetterGuid = Model.IdCode.ToString() })</text>);
      })
)

In TagHelper format, content is not shown for any tabs:

<kendo-tabstrip name="tabStrip">
	<popup-animation>
		<open effects="fade:in" />
	</popup-animation>
	<items>
		<tabstrip-item text="History" icon-class="fa-duotone fa-clock-rotate-left" selected="true">
			<content>@Html.DisplayFor(m => m.History, "LetterHistory")</content>
		</tabstrip-item>

		<tabstrip-item text="Approvers" icon-class="fa-duotone fa-thumbs-up">
			<content></content>
		</tabstrip-item>

		<tabstrip-item text="Details" icon-class="fa-duotone fa-magnifying-glass">
			<content>@Html.DisplayFor(m => m.Approvers, "LetterApprovers")</content>
		</tabstrip-item>

		<tabstrip-item text="Attachments" icon-class="fa-duotone fa-link">
			<content>@await Component.InvokeAsync(viewName, new { LetterGuid = Model.IdCode.ToString() })</content>
		</tabstrip-item>
	</items>
</kendo-tabstrip>
How do I display my content from DisplayFor or ViewComponent?
Aleksandar
Telerik team
 answered on 19 Aug 2022
1 answer
354 views

I have the Upload control in an EditorTemplate as follows:

/Views/Letter/EditorTemplates/LetterAttachmentsManage.cshtml:

@using DACRL.Portal.ColorAdmin.Controllers
@using DACRL.Portal.ColorAdmin.Extensions

@model Guid?

@{
    string[] extensions = { ".jpg", ".png", ".pdf", ".ppt", ".pptx", ".doc", ".docx", ".xls", ".xlsx" };
}

@Html.HiddenFor(m => m)

<kendo-upload name="letterFiles" multiple="true">
    <async save-url="@Url.Action(nameof(UploadController.ChunkSave), ControllerExtensions.Nameof<UploadController>())"
           remove-url="@Url.Action(nameof(UploadController.Remove), ControllerExtensions.Nameof<DashboardController>())"
           auto-upload="true"
           chunk-size="11000" />
    <validation allowed-extensions="@extensions" max-file-size="36700160" />
</kendo-upload>

This template is placed within a form on a parent view as

/Views/Letter/Create.cshtml:

@model LetterModel

@using (Html.BeginForm("", "Letter", FormMethod.Post))
{
	@Html.AntiForgeryToken()

	@Html.HiddenFor(m => m.IdCode)

	<div class="panel mt-20px" data-sortable-id="ui-widget-16">
		<div class="panel-heading bg-da-blue text-white">
			<h4 class="panel-title">RL Info</h4>
		</div>
		<div class="panel-body">
			@Html.EditorFor(m => m, "Letter")
		</div>
	</div>

	<div class="panel mt-20px" data-sortable-id="ui-widget-16">
		<div class="panel-heading bg-da-blue text-white">
			<h4 class="panel-title">Attachments</h4>
		</div>
		<div class="panel-body">
			@Html.EditorFor(m => m.IdCode, "LetterAttachmentsManage")
		</div>
	</div>
	
	<div class="row mt-3">
		<div class="col-md-1">
			<button type="submit" class="btn btn-primary w-100 me-5px" formaction="CreateSave" title="@(Model.IsUpdateCase ? "Update letter" : "Save letter")">@(Model.IsUpdateCase ? "Update" : "Save")</button>
		</div>
		<div class="col-md-1">
			<button type="submit" class="btn btn-default w-100" formaction="CreateSubmit" title="@(Model.IsUpdateCase ? "Update letter & submit" : "Save letter & submit")">Submit</button>
		</div>
	</div>
}

I'm trying to handle the File logic separately so I have the Upload Controller:

public class UploadController : BaseControllerWithAuth<UploadController>
{
    private readonly IWebHostEnvironment hostEnvironment;

    public UploadController(IWebHostEnvironment hostingEnvironment, IHttpContextAccessor httpContextAccess, IUserService userService) : base(httpContextAccess, userService) => hostEnvironment = hostingEnvironment;

    public async Task<ActionResult> ChunkSave([Bind(Prefix = "IdCode.letterFiles")] IEnumerable<IFormFile>? letterFiles, string? metaData, Guid? idCode)
    {
        try
        {
            if (metaData == null)
                return await Save(letterFiles);

            var chunkData = JsonSerializer.Deserialize<ChunkMetaDataModel>(metaData)!;

            if (letterFiles != null)
            {
                foreach (var file in letterFiles) AppendToFile(Path.Combine(hostEnvironment.WebRootPath, Constants.FileUploadPath, chunkData!.FileName), file, idCode?.ToString());
            }

            var fileBlob = new FileResultModel
            {
                uploaded = chunkData!.TotalChunks - 1 <= chunkData.ChunkIndex,
                fileUid  = chunkData.UploadUid
            };

            return Json(fileBlob);
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, $"{nameof(UploadController)} => {nameof(ChunkSave)}: Error: {ex.Message}");
            throw;
        }
    }

    public ActionResult Remove(string[]? fileNames)
    {
        try
        {
            if (fileNames == null) return Content("");

            foreach (var fullName in fileNames)
            {
                var fileName     = Path.GetFileName(fullName);
                var physicalPath = Path.Combine(hostEnvironment.WebRootPath, Constants.FileUploadPath, fileName);

                if (System.IO.File.Exists(physicalPath)) System.IO.File.Delete(physicalPath);
            }

            return Content("");
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, $"{nameof(UploadController)} => {nameof(Remove)}: Error: {ex.Message}");
            throw;
        }
    }

    private void AppendToFile(string fullPath, IFormFile content, string? idCode)
    {
        try
        {
            var basePath = Path.Combine(hostEnvironment.WebRootPath, Constants.FileUploadPath);

            if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);

            var letterPath = Path.Combine(basePath, idCode!);

            if (!Directory.Exists(letterPath)) Directory.CreateDirectory(letterPath);

            using var stream = new FileStream(fullPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            content.CopyTo(stream);
        }
        catch (IOException ex)
        {
            Logger.LogError(ex, $"{nameof(UploadController)} => {nameof(AppendToFile)}: Error: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, $"{nameof(UploadController)} => {nameof(AppendToFile)}: Error: {ex.Message}");
            throw;
        }
    }

    private async Task<ActionResult> Save([Bind(Prefix = "IdCode.letterFiles")] IEnumerable<IFormFile>? letterFiles)
    {
        try
        {
            if (letterFiles == null) return Content("");

            foreach (var file in letterFiles)
            {
                var fileContent  = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
                var fileName     = Path.GetFileName(fileContent.FileName!.Trim('"'));
                var physicalPath = Path.Combine(hostEnvironment.WebRootPath, Constants.FileUploadPath, fileName);

                await using var fileStream = new FileStream(physicalPath, FileMode.Create);
                await file.CopyToAsync(fileStream);
            }

            return Content("");
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, $"{nameof(UploadController)} => {nameof(Save)}: Error: {ex.Message}");
            throw;
        }
    }

}

Note: Due to this being an EditorTemplate, I had to add the 

[Bind(Prefix = "IdCode.letterFiles")]

Now, once the file is being chunked back to the Controller's ChunkSave action, I need to get the value of the model of this EditorTemplate as it will correlate with the primary entity later.

I have tried adding a parameter to the Controller's ChunkSave action as Guid? idCode. But I always get a null there.

How do I go about this dilemma?

 

Alexander
Telerik team
 answered on 17 Aug 2022
1 answer
137 views

I'm not using Newtosoft.Json anymore so I tried to deserialize the metadata like this:

var chunkData = JsonSerializer.Deserialize<ChunkMetaDataModel>(metaData)!;

It's not getting de-serialized properly as all strings are null and all integers are 0s.

Please update this documentation page: ASP.NET Core Upload Component Chunk Upload | Telerik UI for ASP.NET Core & this demo: Chunk Upload in ASP.NET Core Upload Component Demo | Telerik UI for ASP.NET Core soon as I'm stuck for now.

I originally got help from StackOverflow from my question: c# - System.Text.Json.* & deserialization of streams - Stack Overflow

Mihaela
Telerik team
 answered on 17 Aug 2022
1 answer
575 views

This question is two-fold, and I can't seem to find the answers in the documentation. For background info, I'm using the latest version of Wizard (the Tag version) :

  1. How do I hide the reset button? I don't need it for my form.
  2. How do I go about making the Wizard's 'Done' button a submit type of a button, so I can send the form contents to the server? (I can't seem to find how to go about this).

TIA!

Alexander
Telerik team
 answered on 17 Aug 2022
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?