Going through some old code and it appears the e.preventdefault() isn't behaving correctly on a button click. I am not sure how I didn't notice this before, but for some reason it just Simpy isn't doing its job. Page still refreshed even if If statement is executed. Am I missing something, am I blind? Can anyone tell what's going on here?

Also, I would like to add, it definetly gets into the IF statement, because the DIV that needs to be un-hidden does show, however page gets refreshed anyway and it submits which it should not.

Below is my code:

Thank you.


    <form class="form-group" method="get" action="#">
    <div class="row">
        <div class="col-md-12">
            <table class="table table-striped table-hover table-bordered">
                        <th>Command Value</th>
                        <th> </th>
                        <td>@Html.DropDownListFor(o => o.TerminalsDDL, Model.TerminalsDDL, new { id = "ddlTerminalID", @class = "form-control align-middle" })</td>
                        <td onchange="UpdateHelpDescript();">@Html.DropDownListFor(o => o.TerminalCommandLookupsDDL, Model.TerminalCommandLookupsDDL, new { id = "ddlCommandValue", @class = "form-control align-middle" })</td>
                        <td>@Html.TextBoxFor(o => o.UserEnteredTerminalCommands, new { Class = "form-control align-middle", Id = "cmdValueValue" })</td>
                        <td> <input id="btnSaveTerminalCommand" type="button" value="Insert" class="btn btn-primary align-middle" /> </td>


   $(function () {
    $("#btnSaveTerminalCommand").click((e) => {

        if ($("#ddlCommandValue").val() == " " || $("#ddlCommandValue").val() == null || $("#ddlCommandValue").val() == 0 || $("#cmdValueValue").val() == " " || $("#cmdValueValue").val() == null) {

             //window.alert("Please select a valid command.");

        var data = {
            TerminalID: $("#ddlTerminalID").val(),
            CommandID: $("#ddlCommandValue").val(),
            CommandValue: $("#cmdValueValue").val()

            url: '@Url.Action("AddTerminalCommand", "TerminalCommand")',
            type: "POST",
            data: data,
            success: function (response) {
                window.location.href = response.Url;

I'm trying to understand the workflow of a project, and want to instrument on each file that is called.

I've tried to use definition/reference to set breakpoint manually, but it's a huge project that it might miss something this way.

I've also used the step forward button in Visual Studio but it just jumps to the very next line, which makes it impossible to trace the entire project.

Is there something that you can jump to the next file, instead of the next line? Or is there some other tools that could help me understand the flow of the files?

I am trying to follow this article to create a razor component library. This in an of itself it not an issue.

The issue comes when i try to reference this project to my Blazor project.

When i create my Blazor project, it is always created as a .Net Standard project. The Razor component library is created as an Asp.net Core project.

I am unable to create the Blazor project as Asp.net Core. And im unable to create the component library as .Net standard.

What am i doing wrong here?

currently I'm programming a custom authentication filter in ASP.NET MVC5. In order to determine whether the authentication should be performed at all, some database objects should be accessed. Usually this is not a problem, the objects are initialized with the first call of a page. But direct links to a protected page are also used, then OnAuthentication () runs before the controller can initialize the objects.

Is there a way to call a function in the controller from OnAuthentication()?

Or from another class?

Or performing initalization functions before authentication?

Thanks for Your help


I have imported a solution from another machine.Then i build it and run it in my machine. Change my .aspx file and it applied. but when i change the CodeBehind, .cs file it's not applied. Tried methods,

  1. Restart VS and restart machine. (not working)
  2. Save all and build again. (not working)
  3. Delete bin folder contains. (Not Successful)

After I clean bin folder, Now i can't build it again and it throw errors.

Is there any alternative function/solution of the ChrW() ["ChrW return a variant of the string subtype that contains the character represented by charactercode"] which accepts value not in range is -32768–65535 like for character code &#1048711; which leads to "􀂇". Using ChrW() gives error ("Invalid procedure call or argument"), so I want an alternative solution to convert the charactercode to the actual character.

My qeustion is how it compiles C# codes && Html together

string path = string.Format("{0}\\Templates\\RazorExample.cshtml", Directory.GetCurrentDirectory());
string template = System.Text.Encoding.UTF8.GetString(System.IO.File.ReadAllBytes(path));
string returnedView = Engine.Razor.RunCompile(template, "report", typeof(ViewModels.ReportViewModel), reportViewModel, null);
File.WriteAllText(fileName, returnedView);

What I'm trying to do is to return an object from the controller and read all its values one by one in a razor view. The value is going well from view to controller; the issue is when I try to return it from the controller to view. I'm using ASP.NET, Razor Views (HTML5), AJAX and JQuery. Please, let me know if you need further information about this.

These are my three controls in the view:

        <div class="form-group">
            @Html.LabelFor(model => model.IdProducto, "IdProducto", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("IdProducto", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.IdProducto, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.CantidadProducto, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CantidadProducto, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CantidadProducto, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.ValorTotal, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ValorTotal, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ValorTotal, "", new { @class = "text-danger" })

This is my JQuery statement:

    <script type="text/javascript">
        $(function () {
            $('#IdProducto, #CantidadProducto').on('change', function () {
                var IdProducto = $('#IdProducto').val();
                var CantidadProducto = $('#CantidadProducto').val();

                if (CantidadProducto.length > 0) {
                    $.getJSON('@Url.Action("GetProductValue")', { idProducto: IdProducto }, function (data) {
                        $.each(data, function (i, item) {
                            $('#ValorTotal').val(( Number(CantidadProducto) * Number(item.Precio) ));
                else {

And, this is my controller code:

        public JsonResult GetProductValue(string idProducto)
            Producto producto = db.Producto.Find(Convert.ToInt32(idProducto));

            if (producto == null)
                producto = new Producto();

            return Json(producto);

I have an ASP.Net framework (v4.7) web application which I have a build pipeline for in Azure Devops Server (2019).

There is a Visual Studio Build task which builds the solution fine and publishes out the site to the _PublishedWebsites folder. The trouble is, the web.config transform for the release has not been applied and it still has debug="true" set which is not what I want for automated deployment.

The msbuild arguments for the task are: /p:outdir="$(build.artifactstagingdirectory)" and the BuildConfiguration variable for the build is set to release.

When I have published the project using visual studio the web.release.config transform is applied and the debug attribute has been removed from the web.config file in the published content.

Is there something I am missing here?

I'm the newbie on Angular. I am working on a project with Angular7 for frontend and Asp.net for the backend. I Have saved the form data in SQL database with image name but the image is saved in asp.net folder. Now I want to fetch the image to angular but I couldn't find the way. Looking for your valuable suggestions.

I want to show the total number of my data in sql and code c# in aspx directly,but it cant work

I want to write code in aspx and connected to SQL serve

    <td>total count</td>
    <td >

string connection = "SELECT COUNT(*) FROM T_RadioNews";

System.Data.SqlClient.SqlConnection conn = new 
System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = connection;
int count = (int)cmd.ExecuteScalar();

AllTotal = AllTotal + Convert.ToInt32(Total);

I dont know how to fix it ,please help me ,thank a lot

visual studio is unable to build copy of a project.

I copied a project to continue developing that on another PC. also, I made a backup of the database and restored that on destination PC. both database and project look to be copied properly since everything such as project files and folders and database tables are available. the problem is visual studio wont build the project and I encounter an error telling me that IIS express web server was unable to launch.

in short, I am trying to continue my work on another PC but I cant.

I'm attempting to build my own decision tree algorithm in R, but I'm having trouble returning the values I need.


# Weather condition predictors for play
day <- 1:14
outlook <- c("sunny", "sunny", "overcast", "rainy", "rainy", "rainy", "overcast", "sunny", "rainy", "sunny", "sunny", "overcast", "overcast", "rainy")
temperature <- c("hot", "hot", "hot", "mild", "cool", "cool", "cool", "mild", "cool", "mild", "mild", "mild", "hot", "mild")
humidity <- c("high", "high", "high", "high", "normal", "normal", "normal", "high", "normal", "normal", "normal", "high", "normal", "high")
windy <- c(F, T, F, F, F, T, T, F, F, F, T, T, F, T)
play <- c(1,0,1,1,1,0,1,0,1,1,1,1,1,0)
golf <- data.frame(outlook, temperature, humidity, windy, play)

# Calculate entropy
# x - a categorical array
entropy <- function(x) {
    # Total entropy
    h_tot <- 0    
    for (gr in unique(x)) {
        # Calculate proportion of samples in group
        prop <- sum(x == gr) / length(x)        
        # Calculate individual entropy term
        h_term <- -(prop) * log2(prop)        
        # Update total entropy
        h_tot <- h_tot + h_term
    return(round(h_tot, digits = 4))

# Calculate joint entropy
# f1 - first feature
# f2 - second feature
joint_entropy <- function(f1, f2) {
    tab <- table(f1, f2)
    N <- sum(tab)
    # Total entropy
    h_tot <- 0
    for (gr in unique(f2)) {
        pr_gr <- sum(f2 == gr) / N
        h_tot <- h_tot + (pr_gr * entropy(f1[f2 == gr]))
    return(round(h_tot, digits = 4))

# Calculate gain
gain <- function(target, attribute) entropy(target) - joint_entropy(target, attribute) 

# Return attribute with the highest gain, best classifying the given instances
best_attr <- function(target, attributes) names(which.max(sapply(attributes, gain, target = target)))

# Decision tree
decision_tree <- function(examples = NULL, attributes = NULL, target = NULL, parent = NULL, node = NULL, label = NULL) {

    # Checks
    if (is.null(examples) | all(target == target[1])) { # If there are no examples or all targets the same
    } else if (is.null(attributes)) {
        # Return most common target value
        return(names(sort(table(a), decreasing = TRUE))[1] )       
    } else {
        best <- best_attr(target, attributes)
        for (value in (unique(examples[ , best]))) {
            subtab <- examples[examples[ , best] == value, ]
            decision_tree(examples = subtab, attributes = subtab[ , 2:4], target = subtab$play, parent = parent)

decision_tree(examples = golf, attributes = golf[ , 2:4], target = golf$play)

By embedding print functions, I know I get the necessary root, edge, and leaf values for drawing a decision tree. However, I'm struggling to return them. Does anybody have any suggestions?

I am working on a project similar to predict likelihood of a student completing an online course given the performance to a given date. The approach taken so far is very similar to this https://towardsdatascience.com/predicting-success-in-online-education-2b5979fa7016

That is, look at various student features such as GPA as well as performance metrics (quiz results, number of logins, time spent on videos etc) at the midpoint of the course, and try to predict if the student will pass the course at the end. Our current (random forest) model has about 80% accuracy which is decent. But now we want to expand these predictions every week throughout the entire course.

Our current data set uses time units as features. That is, cumulative performance metrics at week 1 is a set of features, cumulative performance week 2 is another set of features etc. So every student has a single record, but the features contain all historical information to a weekly granularity. So the features look something like

studentid   gpa major   age total logins wk1    total time spent wk1    total videos finished wk1   total logins wk2    total time spent wk2    total videos finished wk2   […and so on]

Because of this (and similar to the example in the link), we have to train a model for the specific time point we want to make a prediction for. That is, for week 1 predictions, the data will only have week 1 performance features and the model gets trained on this. For week 2 predictions we have week 1 and week 2 features and so on.

This is all fine and well as the course is only 20 weeks, so we'll end up with 19 models. But let's say we wanted to have daily predictions - we'd have to have over a 100 models. This made me think of if it would make sense to instead use a narrower dataset, where instead the performance being split up in specific time unit features for week 1,2,3 and so on, each student would have a record per week, a single feature for each performance metric, as well as a feature indicating what week (or day) the performance is for.

This would look something like this:

studentid   gpa major   age week #  total logins    total time spent    total videos finished

This would allow a single model to be trained on the data. But with a classification algorithm like RF it will take a single record and try to classify it as pass/not pass. But a single record here will lose a lot of historical information, as it will only have the total performance at that time point. In the wider dataset the model can learn trends with how the performance change over the weeks. In the narrow dataset, the model input will only have a single total performance metric to use as inference. Basically if I feed the RF model a narrow record at say week 10, it will not have any information on how performance changed over time for this particular student, just what the most recent total performance is.

I am hoping to have a discussion how this problem can be approached if you want to make predictions at a higher granularity. To me it seems that eventually it becomes intractable to use the wide data/multiple models version. Say you want to make daily predictions for a four year degree, you would then need 365 x 4 x [number of performance metrics], and use 365x4 different models. But what model should be using with a narrow dataset that can understand the performance over time for a given student? It matters if the student started slow but has been steadily improving performance, vs starting strong and dropping off.

There is also the added complexity of quizzes and tests which only happen a few times per semester and follows a different format than the other performance metrics. In the wide dataset case this would just be a feature that would only be included in the training set if it had happened.

Any input here would be greatly appreciated!

I am trying to write an inference app for my Tensorflow model to deploy on SAP Leonardo Machine Learning cloud instance. All documentation is for image classification. Is there any place where I can find documentation for traditional classification problems using Tensorflow?

Gridview will load file when page loads but it lost datatable plugin after postback or onselectedindexchanged.

I have tried to load datatable again after postback with PageRequestManager but didnt worked for me.

 $(function () {
            $(document).ready(function () {

below is Grid Code

<asp:GridView ID="GridView1" HeaderStyle-CssClass="bg-primary text-white" AutoPostBack="false" ShowHeaderWhenEmpty="True" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_OnSelectedIndexChanged" CssClass="table table-bordered" DataSourceID="SqlDataSource1" ClientIDMode="Static">

                                <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
                                <asp:BoundField DataField="NAME" HeaderText="NAME" SortExpression="NAME" />
                                <asp:BoundField DataField="EMAIL" HeaderText="Email" SortExpression="EMAIL" />
                                <asp:CommandField ShowSelectButton="True" />
                                <div class="text-center">No record found</div>
                            <HeaderStyle CssClass="bg-primary text-white"></HeaderStyle>

Grid should load datatable plugin on page load/postback

I'm trying to implement a custom validator that checks if a file (in a FileUpload control) is bigger than 8mb. However, I can't get the validator to fire, and the page immediately throws a System.Web.HttpException: Maximum request length exceeded.

I added break points, but the were never hit, and I tried increasing the max request time in web.config, but that just resulted in a massive file being uploaded and the validator still didn't fire or hit an break points. I also tried to force validation by adding Page.Validate() to my button click event.

This is what I'm doing in my aspx

           <ul id="commentbox" class="flex-box" visible="true" runat="server">
                            <label>Add Comment To Order</label></li>
                            <asp:TextBox ID="commentTb" TextMode="MultiLine" runat="server"></asp:TextBox></li>
                            <label>Attach File: </label>
                            <asp:FileUpload ID="fileUp" runat="server" /><br />
                            <asp:CustomValidator ID="fileVl" Display="Dynamic" runat="server" ControlToValidate="fileUp" ValidateEmptyText="false" OnServerValidate="fileVl_ServerValidate" ErrorMessage="Invalid File, please make sure the file is 8mb or less, and ithat it is not a script, exe, or shortcut."></asp:CustomValidator></li>
                            <asp:CheckBox ID="boCb" runat="server" Text="Restrict To Buying Office" /></li>
                            <asp:Button ID="commentBtn" runat="server" Text="Submit" OnClick="commentBtn_Click" /></li>
                        <asp:RequiredFieldValidator ID="RcommentVl" runat="server" ControlToValidate="commentTb" ErrorMessage="Comment Required"></asp:RequiredFieldValidator>

This is my validator

protected void fileVl_ServerValidate(object source, ServerValidateEventArgs args)
            if (fileUp.HasFile)
                args.IsValid = fileUp.PostedFile.ContentLength <= 8388608;
                FileInfo fi = new FileInfo(fileUp.FileName);
                String ext = fi.Extension;
                String pattern = "(exe|lnk|url|cs|c|java|sh|py|sql)";
                Match m = Regex.Match(ext, pattern);
                if (m.Success)
                    args.IsValid = false;
                args.IsValid = true;

I need to post webhook info into my database. That is simple enough and I can do that, but I'm having issues updating a line item that has already been inserted into the database. I figured I could change the post I have to a put, but that wouldn't add new entries. I tried to make a solution with this code.

var responseString7 = await url

        if (responseString7.IsSuccessStatusCode)
            var responseString = await url
            .WithHeader("Accept", "application/json")
                trackingNumber = stuff.result.tracking_code,
                EPTrackingStatus = stuff.result.status,
                EPStatusDetails = stuff.result.status_detail,
                EPUpdatedAt = stuff.result.updated_at
            var responseString3 = await "url you cant see"
                .WithHeader("Accept", "application/json")
                    trackingNumber = stuff.result.tracking_code,
                    EPTrackingStatus = stuff.result.status,
                    EPStatusDetails = stuff.result.status_detail,
                    EPUpdatedAt = stuff.result.updated_at

This solution will PUT but not POST. Is there a simpler way to do this?

I'm having some trouble passing parameters on the second to the last page of datatable.

All rows need to have a button wich contains a function to open a modal and show all fields, but only the first page is working.

Using razor to show table values and to send the parameters, inspecting the other pages i can see that all buttons has the value, it's just don't trigger the function "GetData()" on the other pages.

Here's the code:

<div ng-app="testApp" ng-controller="testController">
<table id="customTable" class="table table-responsive table-hover table-striped table-bordered custom-Datatable" style="font-family:'Segoe UI'; width:100%;">
        <tr class="bg-primary text-center" style="color:white">
        @foreach (var item in Model)
            <tr style="font-family:'Segoe UI'" class="text-center">
                    @Html.DisplayFor(model => item.Status)
                    @Html.DisplayFor(model => item.AuthorizationNumber)
                    @Html.DisplayFor(model => item.Remarks)
                    @Html.DisplayFor(model => item.ClientName)
                    @Html.DisplayFor(model => item.MerchantName)
                    <input type="button" value="See More" ng-click="GetData('@item.Id')" class="btn btn-outline-primary" />


Here's my js:

    var app = angular.module('testApp', []);
    app.controller('testController', function ($scope, $http) {

            $scope.GetData = function (id) {
            $http.post('/WexReportInfoes/GetTransaction', { InfoId: id }).then(function (result) {
                if (result.data.error == null) {
                    $scope.object = result.data;
                else {



Someone already had this problem and can help me?

So I have a dropdown with Credit Card types. The full names of the cards show in the dropdown and each option has an associated Value that is an abbreviation of the name. For some reason the controller is receiving Mastercard instead of MC.

In my controller I have

var list = new List<SelectListItem>
    new SelectListItem{ Text = "American Express", Value = "AX" },
    new SelectListItem{ Text = "Discover", Value = "DI" },
    new SelectListItem{ Text = "Mastercard", Value = "MC" },
    new SelectListItem{ Text = "Visa", Value = "VI" }
model.Card.CreditCardTypes = list;

and in my razor code I have

@Html.DropDownListFor(m => m.Card.CreditCardType, Model.Card.CreditCardTypes, "Please Select", new { @class = "form-control ", onchange = "javascript:card_type_changed(this.value);" })

but for some reason this is returning the Text field to my controller instead of the Value field. I have no idea why.

Also here is the rendered HTML

<select class="form-control" data-val="true" data-val-required="Please enter the card type" id="Card_CreditCardType" name="Card.CreditCardType" onchange="javascript:card_type_changed(this.value);"><option value="">Please Select</option>
    <option value="AX">American Express</option>
    <option value="DI">Discover</option>
    <option value="MC">Mastercard</option>
    <option value="VI">Visa</option>

Someone requested to see the Javascript function set in the onchange

function card_type_changed(value) {
    if (value == 'AX') {
        document.getElementById('Card_CardNumD').maxLength = 3;
        document.getElementById('Card_SecurityCode').maxLength = 4;
        document.getElementById('Card_CardNumD').value = '';
    } else {
        document.getElementById('Card_CardNumD').maxLength = 4;
        document.getElementById('Card_SecurityCode').maxLength = 3;
        document.getElementById('Card_SecurityCode').value = '';

How to generate server side dotnet core api code using visual studio code from yaml file