The process of invoking a JavaScript function within a Kendo Grid column template using Razor syntax

I have successfully set up a Kendo Grid using MVC4 and Razor syntax. This grid is designed to show log entries retrieved from a database table. The LogText column in the database contains text with Windows newline characters that I want to replace with line break tags for better readability on the front-end. In order to achieve this, I created a JavaScript function that will be called from a column template within the grid. The grid itself utilizes server binding. However, I am having trouble finding the correct syntax to make a JavaScript call from within the template, especially with Razor syntax involved. Any assistance or guidance on this matter would be greatly appreciated.

Below is a snippet of my code:

@model IEnumerable<Core.Models.ShipmentLog>

@{
    ViewBag.Title = "ShipmentLog";
}

<h2>ShipmentLog</h2>
@(Html.Kendo().Grid(Model)
    .Name("ShipmentLogGrid")
    .Columns(columns=>
    {
        columns.Bound(bl => bl.UserName);
        columns.Bound(bl => bl.LogTime);
        columns.Bound(bl => bl.LogType);
        columns.Bound(bl => bl.LogText).Width(600).Encoded(false).Template(#=  GetHtmlNewLinesString(@item.LogText) #);

    })

)

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script type="text/javascript">
    function getHtmlNewLinesString(text) {
        return text.replace('\n/g', '<br />');
    }
</script>

Answer â„–1

@(Html.Kendo().Grid(Model)
.Name("Details")
.Columns(columns =>
{
    columns.Bound(m => m.SubSystemOrderId).Title("Subsys #");
    columns.Bound(m => m.Description).Title("Description").Template(@<text><a href="javascript: void(0);" onclick="return window.top.DisplayExternalOrderDetails('@item.SubSystemOrderId', '@item.OrderDetailTypeId', '@item.ProposalId', '@ViewBag.MyOpExUser', '@ViewBag.selectedOpportunityId')">@item.Description</a></text>);
    columns.Bound(m => m.SubSystemStatusName).Title("Status");
    columns.Bound(m => m.GrossRevenue).Title("Gross Revenue").Format("{0:c}");
    columns.Bound(m => m.IncludeInForecast).Title("Include In Forecast").Template(m=>m.IncludeInForecast ? "Yes" : "No");
    columns.Bound(m => m.ProposalId).Title("Proposal Id").Visible(false);

})
)

yet another example

columns.Bound(m => m.OpportunityName).Title("Opportunity Name").ClientTemplate("<a href='javascript: void(0);' onclick=\"return openMSDynamicsWindow('#= OpportunityUrl #');\">#= OpportunityName #</a>").HtmlAttributes(new { @class = "k-link" });

You will observe that I am passing into the function '#= OpportunityUrl #'. This is how you can extract values from the model. #= OpportunityName # will be the text for the link.

This is a more intricate example, the possibilities are endless. Overcoming the challenges related to string manipulation in this context can be quite frustrating

columns.Bound(m => m.Dollars).Title("").ClientTemplate(
          "# if (Dollars == null) { #" +
          "" +
          "# } else if (Dollars == 0) { #" +
          "<div>#= kendo.toString(Dollars, 'c') #</div>" +
          "# } else if (Count > 0) { #" +
          "<a href='javascript: void(0);' onclick=\"return window.top.openOrderDetails('#= Count #','#= Type #','#= DetailId #','#= OrderId #','#= User #','#= SelectedId #');\">#= kendo.toString(Dollars, 'c') #</a>" +
          "# } #"
          )

Answer â„–2

One can accomplish this task without the need for JavaScript, but if you want to delve deeper into using templates, take a look at @C Sharper's response.

Explore this link for more insights on utilizing templates

columns.Bound(bl => bl.LogText)
       .Template(@<text>@item.LogText.Replace(System.Environment.NewLine, "<br />"))
       .Width(600)
       .Encoded(false);

Answer â„–3

Sharing this method that might be useful to someone. I am utilizing it to create a unique id within the textbox. Additionally, you can easily incorporate an onclick or on blur event and pass along the element ID.

 Html.Kendo().Grid((List<RadCarePlus.V2.Web.Models.Facilities>) ViewData["FacilitiesList"])
.Name("Facilities")
.Columns(columns =>
{   int i = 0;
    columns.Bound(c => c.ProviderID).Title("Provider Number").Width(150).HtmlAttributes(new { style = "text-align:center; white-space: nowrap;" }).HeaderHtmlAttributes(new { style = "text-align:center; white-space: nowrap;" });
    columns.Bound(c => c.NPI).Title("NPI").Width(150).HtmlAttributes(new { style = "text-align:center; white-space: nowrap;" }).HeaderHtmlAttributes(new { style = "text-align:center; white-space: nowrap;" });
    columns.Bound(c => c.ProviderFirstName).Template(c => c.ProviderFirstName + " " + c.ProviderLastName).Title("Provider Name").Width(140).HtmlAttributes(new { style = "text-align:center; white-space: nowrap; text-decoration: underline;" }).HeaderHtmlAttributes(new { style = "text-align:center; white-space: nowrap;" });
    columns.Bound(c => c.AddressLine1).Template(c => c.AddressLine1 + " " + c.AddressLine2 + "<BR>" + c.City + " " + c.State + " " + c.Zipcode).Title("Address").Width(140).HtmlAttributes(new { style = "text-align:left; white-space: nowrap;" }).HeaderHtmlAttributes(new { style = "text-align:left; white-space: nowrap;" });
    columns.Bound(c => c.Email).Template(c => "<input type='text' name='AdminEmail' id='" + (i = i + 1) + "' value='" + c.Email + "'> ").Title("Administrator").Width(140).HtmlAttributes(new { style = "text-align:center; white-space: nowrap; text-decoration: underline;" }).HeaderHtmlAttributes(new { style = "text-align:center; white-space: nowrap;" });          
})
.Sortable(sortable => sortable.AllowUnsort(false))
.DataSource(dataSource => dataSource.Server().PageSize(5)
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to logout when the select event occurs using the key?

I am trying to figure out how to log out the key value when the select event is triggered. Specifically, I want to access the key={localState.id} within the <select></select> element in my HTML. This key value is crucial for a conditional stat ...

The application built using Asp.net Mvc is unable to access the request path once the

I am looking to implement 301 routing on my Asp.net Mvc 4 website. I am currently reading the URL from the Application_BeginRequest Callback in the global.asax file. However, I am facing an issue when trying to read URLs that contain additional parameter ...

Looping through a JSON object in Highcharts to populate data series

I'm brand new to Java Script and I'm on a mission to loop through my JSON object and populate the Highcharts data series. You can take a look at my static demonstration of what I'm trying to achieve on JS Fiddle. Check out JsFiddle here Any ...

What are the steps to modify a tooltip that has already been displayed?

Usually, the tooltip appears when hovering a mouse cursor over an element. I would like to change the tooltip to a new one after approximately 10 seconds each time it appears. This means that every time you hover over an element, the tooltip initially disp ...

The process of rendering children elements in React

I have a question about managing children components in React. While there are resources available explaining this concept, I believe a more detailed explanation would be helpful. Let's consider the structure of my React component tree, which looks l ...

Is there a way for modules to utilize functions and variables from the server that they depend on?

Below is a simple example of the concept I am experimenting with: FileA.js module.exports = { doSomething () { console.log(data['a']); } } FileB.js module.exports = { doSomething () { console.log(data['b']); } } a ...

Can the tag function arguments be employed to generate an identical sequence of literals and placeholders?

A section from the tutorial on template strings at this link includes an interesting example: var say = "a bird in hand > two in the bush"; var html = htmlEscape `<div> I would just like to say : ${say}</div>`; // A basic tag function func ...

Angular's UI Modal: utilizing inline template and controller functionality

I am looking to create a simple confirmation box using UI-modal, which I have used successfully for more complex modals in the past that load their template and controller from external files. However, this time I want something even simpler - just a basi ...

Guide to accessing a method from a separate file with the help of an event bus

I'm working on CreateEntryStepper.vue where I have a button that needs to call a function in CreateEntryStepperImageUpload.vue when pressed. I understand that event busses need to be used, but I am unsure about what exactly needs to be passed and how ...

Tips for integrating JQuery into a JavaScript file seamlessly without causing conflicts

Similar Question: Dynamically Including jQuery using JavaScript if it's not already present I am currently working on a project that requires users to embed a piece of javascript code on their websites, similar to Google Analytics. My main concer ...

What is the most effective method for displaying an error code when a JavaScript error occurs?

I'm currently dealing with a library that is throwing errors: throw new Error('The connection timed out waiting for a response') This library has the potential to throw errors for various reasons, making it challenging for users to handle ...

The script for choosing pages is malfunctioning

I'm having trouble with a script on my website. It works on the index page, but not on other pages. <div id="pages"></div>   <script>      a = location.href;      b = a.split('-');      c = b.length;    ...

Error VM5601:2 encountered - Unexpected token "<" found in JSON at position 10

I am trying to retrieve data using Ajax and jQuery, but I keep encountering an error that I cannot figure out how to fix. VM5601:2 Uncaught SyntaxError: Unexpected token < in JSON at position 10 Below is the code I am working with. Model public f ...

How to turn off JavaScript using Selenium WebDriver?

Recently, I encountered a problem with my program that tests some of our sites with javascript disabled. Everything was working perfectly until we upgraded from WebDriver 2.4.5 to the latest version. Now, I'm faced with this error message: java.lang. ...

Challenges related to JavaScript relate to the scripting language within a text area

Currently, I am working on integrating the mention functionality using (@) in a textarea that retrieves data from MySQL database. Below is the code snippet that I am utilizing: var start=/@/ig; // @ Match var word=/@(\w+)/i ...

A guide to implementing Quasar Framework and/or Vue3 using Bun.js

After using the bun create [..] command to easily create a react and a next project by following the instructions on the bun git repository (note: additional instructions are available at bun.sh), I encountered a problem with setting up quasar/vue. While ...

What is the best way to horizontally scroll to a selected item within a scrollable div using React?

I'm working on a project that involves creating a horizontal scrollable list. The goal is to have the list automatically scroll to the selected item, centering it in the view. While attempting to implement this feature using React, I've encounte ...

Size attribute set to 0 for an HTML input element

When an input element is rendered, it should have a width of 0. However, when there is no text in the input, the width should remain 0. To achieve this, you can use the following jQuery code: $('input').on('input', function () { $(th ...

The axios requests are sent to the backend API, but the webpage remains empty without

I am trying to retrieve a base64 encoded image from my local backend by making a local API call. The logging on the backend confirms that axios is successfully calling the API, however, the frontend displays an empty page with no data. What could be caus ...

What steps can I take to ensure that my dynamically loaded script is fully loaded prior to executing a particular function?

I am facing an issue with a dynamically loaded script in a component. The script contains a function that is used within another function like window["scriptFunction"]. The problem arises when this function is sometimes called before the script i ...