Using the following code snippet in WinForms, I am successfully able to upload documents through a REST API. But as soon as I move to ASP.NET, it throws a NullReferenceException.

public async Task<string> TestUpload()
    {
        const string cServerBaseAddress = "https://test-testrestservice.abcd.com/";
        const string cFilename = @"D:\temp\Test.txt";
        const string cUrl = "{0}abc/dms/api/v1/crmdocuments/?BusinessUnit={1}&AccountID={2}&DocumentType={3}&Description={4}&Filename={5}";
        string businessUnit = "XYZ";
        string accountID = "ABCCompany";
        string docType = "Affidavit";
        string description = @"\%&description&%/";
        string responseContent = string.Empty;
        try
        {
            string url = string.Format(cUrl, cServerBaseAddress,
            WebUtility.UrlEncode(businessUnit), WebUtility.UrlEncode(accountID),
            WebUtility.UrlEncode(docType), WebUtility.UrlEncode(description),
            WebUtility.UrlEncode(Path.GetFileName(cFilename)));
            using (HttpClient client = GetClient(cServerBaseAddress))
            {
                using (HttpResponseMessage response = await client.PostAsync(url, new ByteArrayContent(File.ReadAllBytes(cFilename))))
                {
                    responseContent = await response.Content.ReadAsStringAsync();
                    response.EnsureSuccessStatusCode();
                    string newContentId = Newtonsoft.Json.Linq.JToken.Parse(response.Content.ReadAsStringAsync().Result).ToString();
                    return newContentId;
                }
            }
        }

I've debugged the client, url, and ByteArrayContent, and none of them is null. But I am still getting an unhandled exception.

Here are the details of the exception:

   at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean setImpersonationContext)
   at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext)
   at System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(SendOrPostCallback callback, Object state)
   at System.Web.LegacyAspNetSynchronizationContext.CallCallback(SendOrPostCallback callback, Object state)
   at System.Web.LegacyAspNetSynchronizationContext.Post(SendOrPostCallback callback, Object state)
   at System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.PostAction(Object state)
   at System.Threading.Tasks.AwaitTaskContinuation.RunCallback(ContextCallback callback, Object state, Task& currentTask)
--- End of stack trace from previous location where exception was thrown ---
   at System.Threading.Tasks.AwaitTaskContinuation.<>c.<ThrowAsyncIfNecessary>b__18_0(Object s)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

Tradier API: https://developer.tradier.com/getting_started Codes for request to the Tradier API is available in all languages php,curl,perl,python,Go,ruby except C#

Here is python code for get json response from tradier api

       import httplib

       # Request: Market Quotes 
       (https://sandbox.tradier.com/v1/markets/quotes?symbols=spy)
       connection = httplib.HTTPSConnection('sandbox.tradier.com', 443,timeout = 30)

       # Headers
       headers = {"Accept":"application/json",
       "Authorization":"Bearer Hu2fgA4jAHr9L4NucOpJWx1JhzNa"}

       # Send synchronously
       connection.request('GET', '/v1/markets/quotes?symbols=spy', None, 
       headers)
       try:
       response = connection.getresponse()
       content = response.read()
       # Success
       print('Response status ' + str(response.status))
       except httplib.HTTPException, e:
       # Exception
       print('Exception during request')

i need this code in to asp.net C# to make request

Here is my Converted code in c#

    string url="https://sandbox.tradier.com/v1/markets/quotes?symbols=spy";
    HttpWebRequest request =(HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "appication/json";
            request.Headers.Add("Accept", "appication/json");
            request.Headers.Add("Authorization","Bearer 
             Hu2fgA4jAHr9L4NucOpJWx1JhzNa")

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        string myResponse = "";
        using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
        {
            myResponse = sr.ReadToEnd();
        }
        Response.Write(myResponse);

I got this error

       the-remote-server-returned-an-error-401-unauthorized

I am trying to update an entry in a database on an aspx page. I have an aspx page which shows an items with three properties. When I click edit an item to update one or all of the properties and click on update, I get the following errors are:

System.Data.SqlClient.SqlException: 'Incorrect syntax near '('.'

My aspx code is as follows:

<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <div class="col-lg-12">
            <div class="form-group alert alert-warning">
               <asp:label runat="server" ID="lblNewsEdits">Please edit news details below</asp:label>
            </div>
            <div class="form-group">
                <asp:TextBox name="txtTitle" id="txtTitle" tabindex="1" class="form-control" placeholder="Title" value="" runat="server"></asp:TextBox>
            </div>
            <div class="form-group">
                <asp:TextBox name="txtDate" id="txtDate" tabindex="1" class="form-control" placeholder="Enter Today Date DD/MM/YYYY" value="" runat="server"></asp:TextBox>
            </div>
            <div class="form-group">
                <asp:TextBox namee="txtNewscontent" name="txtNewscontent" id="txtNewscontent" tabindex="2" class="form-control" placeholder="News Content" runat="server"></asp:TextBox>
            </div>
            <div class="form-group">
                <div class="row">
                    <div class="col-sm-6 col-sm-offset-3">
                        <input type="submit" name="btnEdit" id="btnEdit" tabindex="1" class="form-control btn btn-warning" value="Edit"/>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-1 col-md-offset-11">
                        <a href="/Backend/Default.aspx" class="btn btn-default pull-right">Back</a>
                    </div>
                </div>    
            </div>
        </div>
    </div>
</div>

My aspx.cs code is:

 protected void Page_Load(object sender, EventArgs e)
    {
        {
            string q = Request.QueryString["id"];
            int id = 0;
            int.TryParse(q, out id);

            if (Session["username"] == null)
                Response.Redirect("Login.aspx");

            if (IsPostBack)
            {
                EditNews(id);
                Response.Redirect("~/Backend");
            }
            else
            {
                PopulateNews(id);
            }
        }
    }
    private void EditNews(int id)
    {
        //Create a SQL Connection - get the connection string from the web.config
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString);
        //define the SQL statement you wish to run - use @ placeholders to populate parameters
        string sqlStatement = "UPDATE News (Title, DatePosted, NewsContent) Values (@Title,@DatePosted,@NewsContent);";
        //Set up the SQL Command
        SqlCommand command = new SqlCommand(sqlStatement, connection);
        //Populate the placeholders with parameter values
        command.Parameters.AddWithValue("@Title", txtTitle.Text);
        command.Parameters.AddWithValue("@DatePosted", Convert.ToDateTime(txtDate.Text));
        command.Parameters.AddWithValue("@NewsContent", txtNewscontent.Text);
        //open a connection to the database (NOTE! dont forget to close this when you are done)
        connection.Open();
        //Run the SQL statement against the database
        command.ExecuteNonQuery();
        command.Dispose();
        //NOTE! close the connection
        connection.Close();
    }
    private void PopulateNews(int id)
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString);
        connection.Open();
        string query = "SELECT Title, DatePosted, NewsContent FROM News WHERE Id = @id";

        SqlCommand command = new SqlCommand(query, connection);
        command.Parameters.AddWithValue("@id", id);
        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            txtTitle.Text = reader["Title"].ToString();
            txtDate.Text = reader["DatePosted"].ToString();
            txtNewscontent.Text = reader["NewsContent"].ToString();
        }
        reader.Close();
        connection.Close();
    }

My table properties are:

CREATE TABLE [dbo].[News] (
[Id]          INT            IDENTITY (1, 1) NOT NULL,
[Title]       NVARCHAR (100) NOT NULL,
[DatePosted]  DATE           NOT NULL,
[NewsContent] NTEXT          NOT NULL,
[IsRead]      BIT            DEFAULT ((0)) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

Any ideas?

I am working on a small project to build an ecommerce website. I have an admin side to the website where the admin can upload a product and it will go directly to the front end of the website. I have a used a "file upload", where the admin can select an image to add to the product, however, when the product has been uploaded all the product details show apart from the picture.

Here is the code:

HttpPostedFile postedFile = ProductImage.PostedFile;
        string fileName = Path.GetFileName(postedFile.FileName);
        string fileExtension = Path.GetExtension(fileName);
        int fileSize = postedFile.ContentLength;

        if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".bmp" ||
            fileExtension.ToLower() == ".gif" || fileExtension.ToLower() == ".png")
        {
            Stream stream = postedFile.InputStream;
            BinaryReader binaryReader = new BinaryReader(stream);
            byte[] bytes = binaryReader.ReadBytes((int)stream.Length);

The "byte" array is then added to the MySql database without any other conversions.

command.CommandText = "Insert into productdetails(Photo) values('" bytes"')";

It is stored as "varbinary" in the database.

When I attempt to upload the picture I only get a small picture icon where the photo should be.

Please could someone help! I have had this error for ages!

Thanks all Note: The ID for the file upload is "ProductImage", so when the code says ProductImage it is talking about the file upload.

I have setup this custom route for a method in a controller:

[HttpPost, Route("imagconv/{format1}/to/{format2}")]
public HttpResponseMessage imagconv( [FromUri] string format1, [FromUri] string format2)

The route on the controller is:

[RoutePrefix("convert")]
public class DocumentConvertController : ApiController

And I am trying to call it in Postman with this example:

http:// ...server... /convert/imageconv/psd/to/png

And instead of getting the result, I am getting a 404 error.

Here is what is in my RouteConfig:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

Does anyone know why this is not working? This seems straightforward. Thanks in advance!

I have the following nested Girdview. The issue is when the parentgrid is loaded, it is showing 2 childgrids, one by the expand img, one below each row when I click on the expand img. The one by the expand img is unexpected and unwanted. Can someone help me fix this issue?

ASPX

<asp:GridView ID="gvLotDetails" runat="server" Width="600px" BackColor="White" AutoGenerateColumns="False" OnRowDataBound="gvLotDetails_DataBound" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" Height="169px" DataKeyNames="ItemNumber">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <img alt = "" style="cursor: pointer" src="Images/plus.png" />
                <asp:Panel ID="pnlLotDetailsExtend" runat="server">
                    <asp:GridView ID="gvLotDetailsExpand" runat="server" AutoGenerateColumns="false" DataKeyNames="Slab">
                        <Columns>
                            <asp:BoundField DataField="Slab" SortExpression="Slab" ReadOnly="True" HeaderText="Slab" />
                            <asp:BoundField DataField="Size" SortExpression="Size" ReadOnly="True" HeaderText="Size" />
                            <asp:BoundField DataField="Sqft" SortExpression="Sqft" ReadOnly="True" HeaderText="Sqft" />
                            <asp:BoundField DataField="Block" SortExpression="Block" ReadOnly="True" HeaderText="Block" />
                            <asp:BoundField DataField="Totalweight" SortExpression="Totalweight" ReadOnly="True" HeaderText="Totalweight" />
                            <asp:BoundField DataField="country" SortExpression="country" ReadOnly="True" HeaderText="Country" />
                        </Columns>
                        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" HorizontalAlign="Right" />
                        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                        <HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000" />
                        <AlternatingRowStyle BackColor="White" HorizontalAlign="Left" Font-Underline="true" />
                    </asp:GridView>
                </asp:Panel>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="ItemNumber" SortExpression="ItemNumber" 
            ReadOnly="True" HeaderText="ItemNumber" />
        <asp:BoundField DataField="whse" SortExpression="whse" ReadOnly="True" 
            HeaderText="Warehouse" />
        <asp:BoundField DataField="Bundle" SortExpression="Bundle" ReadOnly="True" 
            HeaderText="Bundle" />
    </Columns>
    <PagerSettings Position="TopAndBottom" />
    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" HorizontalAlign="Right" />
    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
    <HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000" />
    <AlternatingRowStyle BackColor="White" HorizontalAlign="Left" Font-Underline="true" />
</asp:GridView>

JavaScript

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $("[src*=plus]").live("click", function () {
        $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
        $(this).attr("src", "Images/minus.png");
    });
    $("[src*=minus]").live("click", function () {
        $(this).attr("src", "Images/plus.png");
        $(this).closest("tr").next().remove();
    });
</script>

Code Behind

A button event triggers GetDeatils()

private void GetDetails()
{
    query = "SELECT ItemNumber, WHSE, Bundle FROM labels_slab_details WHERE lot= '" + this.txtLot.Text.Trim() + "' and containernumber='" + this.ddlCont.SelectedValue + 
            "' GROUP BY ItemNumber, WHSE, Bundle ORDER BY Bundle, ItemNumber";
    cn = new SqlConnection(cnBCStr);
    SqlDataAdapter da = new SqlDataAdapter(query, cn);
    ds = new DataSet();
    da.Fill(ds);
    if (ds.Tables[0].Rows.Count > 0)
    {
        this.gvLotDetails.DataSource = ds.Tables[0];
        this.gvLotDetails.DataBind();
        this.gvLotDetails.Visible = true;
    }
    else
    {
        this.gvLotDetails.Visible = false;
        this.errLabelDetail.Text = "* Create Bundle Data First! ";
        return;
    }
}

protected void gvLotDetails_DataBound(object Sender, GridViewRowEventArgs Ea)
{
    if (Ea.Row.RowType == DataControlRowType.DataRow)
    {
        string ItemNumber = gvLotDetails.DataKeys[Ea.Row.RowIndex]["ItemNumber"].ToString();
        GridView gvLotDetailsExpand = Ea.Row.FindControl("gvLotDetailsExpand") as GridView;
        gvLotDetailsExpand.DataSource = GetData(string.Format("SELECT slab, size, sqft, block, totalweight, country FROM labels_slab_details WHERE LOT='" + this.txtLot.Text + "' AND ItemNumber='" + ItemNumber + "'"));
        gvLotDetailsExpand.DataBind();
    }
}

private static DataTable GetData(string query)
{
    string cnBCStr = System.Configuration.ConfigurationManager.ConnectionStrings["conBarcodes_SQLWeb"].ConnectionString;
    using (SqlConnection cn = new SqlConnection(cnBCStr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter da = new SqlDataAdapter())
            {
                cmd.Connection = cn;
                da.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    return dt;
                }
            }
        }
    }
}

I updated the code to remove some changes I made for testing the issue.

I found nice article about "how configure .NET CORE with VUE SSR and Webpack".

Everything works nice, but when I want use lazy loading component in routes I got error.

An unhandled exception occurred while processing the request.
NodeInvocationException: Cannot find module '1.js'
Microsoft.AspNetCore.NodeServices.HostingModels.HttpNodeInstance+<InvokeExportAsync>d__7.MoveNext()

I tried to debug .net spaservices code and I found where exception is throwed - in this method:

Module._resolveFilename = function(request, parent, isMain) {
  if (NativeModule.nonInternalExists(request)) {
    return request;
  }

  var resolvedModule = Module._resolveLookupPaths(request, parent);
  var id = resolvedModule[0];
  var paths = resolvedModule[1];

  // look up the filename first, since that's the cache key.
  debug('looking for %j in %j', id, paths);

  var filename = Module._findPath(request, paths, isMain);
  if (!filename) {
    var err = new Error("Cannot find module '" + request + "'");
    err.code = 'MODULE_NOT_FOUND';
    throw err;
  }
  return filename;
};

Id property above contains this value: 0.js

Paths: property above contains this array of paths

"C:\Projects\SmartSystem\DEV\Fibit.Bruno\src\Fibit.Bruno.Web.Mvc\EshopClientApp\node_modules\vue-server-renderer\node_modules"
"C:\Projects\SmartSystem\DEV\Fibit.Bruno\src\Fibit.Bruno.Web.Mvc\EshopClientApp\node_modules"
"C:\Projects\SmartSystem\DEV\Fibit.Bruno\src\Fibit.Bruno.Web.Mvc\node_modules"
"C:\Projects\SmartSystem\DEV\Fibit.Bruno\src\node_modules"
"C:\Projects\SmartSystem\DEV\Fibit.Bruno\node_modules"
"C:\Projects\SmartSystem\DEV\node_modules"
"C:\Projects\SmartSystem\node_modules"
"C:\Projects\node_modules"
"C:\node_modules"
"C:\Projects\SmartSystem\DEV\Fibit.Bruno\src\Fibit.Bruno.Web.Mvc\node_modules"
"C:\Users\Martin\.node_modules"
"C:\Users\Martin\.node_libraries"
"C:\Program Files\nodejs\lib\node"

ERROR:

err = Error: Cannot find module '0.js' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Module.require (module.js:497:17) at require (internal/module.js:20:19) at r (C:\Projects\SmartSystem\DEV\Fibit.Bruno\src\Fibit.Bruno.Web.Mvc\EshopClientApp\node_modules\vue-server-renderer\build.js:8152:16) at Function.requireEnsure [as e] (__vue_ssr_bundle__:41:25) at Object.module.exports.Object.defineProperty.value (__vue_ssr_bundle__:16233:40) at __webpack_require__ (__vue_ssr_bundle__:27:30) at Object.module.exports.Object.defineProperty.value (__vue_ssr_bundle__:10431:15) at __webpack_require__ (__vue_ssr_bundle__:27:30), request = "0.js"
err.code = 'MODULE_NOT_FOUND'

ROUTER:

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const router = new VueRouter({
    mode: 'history',
    routes: [
        { path: '/', component: resolve => require(['../components/Dashboard.vue'], resolve) },
        { path: '/messages', component: resolve => require(['../components/Messages.vue'], resolve) },
    ]
});

export default router;

WEBPACK config:

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');

module.exports = (env) => {
    const isDevBuild = !(env && env.prod);

    const sharedConfig = () => ({
        stats: { modules: false },
        resolve: { extensions: ['.js', '.vue'] },
        output: {
            filename: '[name].js',
            publicPath: '/dist/'
        },
        module: {
            rules: [
                {
                    test: /\.vue$/,
                    loader: 'vue-loader',
                },
                {
                    test: /\.js$/,
                    loader: 'babel-loader',
                    include: __dirname,
                    exclude: /node_modules/
                },
                { 
                    test: /\.css$/, 
                    loader: "style-loader!css-loader" 
                }
            ]
        }
    });

    const clientBundleOutputDir = '../wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig(), {
        entry: { 'main-client': './client.js' },
        output: {
            path: path.join(__dirname, clientBundleOutputDir)
        }
    });

    const serverBundleConfig = merge(sharedConfig(), {
        target: 'node',
        entry: { 'main-server': './server.js' },
        output: {
            libraryTarget: 'commonjs2',
            path: path.join(__dirname, '../wwwroot/dist')
        },
        module: {
            rules: [
                {
                    test: /\.json?$/,
                    loader: 'json-loader'
                }
            ]
        },
    });

    return [clientBundleConfig, serverBundleConfig];
}

How solve problem with lazy loading with SSR, .NET CORE and Webpack ? Do anybody have any idea ? Thanks!

I am working on a asp.net project and want to make sure doing it the right way.

I have attached my current environment setup. I need to expose data in JSON format to users. I am planning to create two web APIs. First one(on DMZ server) will get data from database and expose it to Web server. Second one will read data from DMZ server and expose it to outside world. Please let me know if there is a better way. Thank you for all the help.

3-tier environment

The issue that I am having is that when I click the submit button on my "editmeal" page, it still submits a post back when there is validation errors to the back-end, even though I am sending false return statement back. I am using the same code on a different page (The same validation) and it works.

function Custom_Validate(element) {
//Set the current validate to true
var validate = true;
//Checks to see there is an element attached to it so it can check that only event and not every single one, but if there is not it will check everything due to it thinking it is a form submission
$(element ? element : '[validationgroupname="AllValidators"]').each(function () {
    //Assigns $(this) to a variable
    var $this = $(this);
    //Takes the poroperty tagName and puts it lower case
    switch ($this.prop('tagName').toLowerCase()) {
        case 'input':
            {
                //This will check to see if the textbox has any value and if not it willput validate to false and show the error
                if ($this.val().length == 0) {
                    $('#' + $this.data('describeby')).text('Meal Name is Not Valid').show();
                    validate = false;
                    return;

                }
                    //This will check the regex expression for special characters and show the error if there is some found and set validate to false
                else if (!/^[a-zA-Z0-9-/ ]*$/.test($this.val())) {
                    $('#' + $this.data('describeby')).text('Meal Name Contains an Invalid Character').show();
                    validate = false;
                    return;
                }
                    //If both properties do not match then it will hide the error
                else {
                    $('#' + $this.data('describeby')).hide();
                    return;
                }
            }
        case 'select':
            {
                //Checks to see if the value is not 0 which is the orginal select statement. If it is it will show the error and set the validate to false
                if ($this.val() == 0) {
                    $('#' + $this.data('describeby')).text('Please Choose an Item Category').show();
                    validate = false;
                    return;
                } else {
                    $('#' + $this.data('describeby')).hide();
                    return;
                }
            }
    }
});
//Return the validate
return validate;
}

  function Form_Validate() {
    //When this is called by the onClientClick button it will send a function 
    call to validate all fields and return the update
    var validated = Custom_Validate();
    //If the update is true, then it will continue to send the ajax call
    if (validated) {
       //Make the postData look similar to the meal food view model
       var postData = {
          MealName: $('#ContentPlaceHolder1_EditMealName').val(),
          MealCategoryID: $('#ContentPlaceHolder1_EditCategoryName').val(),
          FoodID: []
    };
    //Search through each of thsese IDS
    $('#editItemDropdownList_0, #editItemDropdownList_1, 
    #editItemDropdownList_2, #editItemDropdownList_3, #editItemDropdownList_4')
        .each(function () {
            //On each ID push the value with aradix of 10
            postData.FoodID.push(parseInt($(this).val(), 10));
        });
    //Send the ajax call through AddMeal.aspx
    $.ajax({
        url: "http://localhost:63591/EditMeal.aspx",
        method: 'POST',
        data: { data: JSON.stringify(postData) }
    });
   }
//This will return false on all, to avoid a double submissions of viewstate
return false; // Sends false to stop a double post back
  }

Below is the asp.net code that takes the return statement

 <div class="form-group">
                    <div class="row">
                        <div class="col-xs-12 text-center">
                            <asp:Button ID="EditMealButton" runat="server" OnClientClick="return Form_Validate();" Text="Submit" CssClass="btn btn-success"
                                         ValidationGroup="AllValidators" />
                            <asp:hyperlink cssclass="btn btn-default" navigateurl="~/Food.aspx" runat="server" text="Back" />
                        </div>
                    </div>
                </div>

Any Idea as to why this would work on one page but not the other?

https://pastebin.com/bLfqCrNK - Full code for the page that works.

https://pastebin.com/Cvxa1ECG - Full code for the page that does not work

I'm new to json and I need help with following json string, I need to fetch values into string variables to save into db.

{
"message_id": {"8624389": "447123456789"},
"sent_text": "Test message",
"parts_count": 1
}

how can I get values of message_id, sent_text and parts_count into variables?

Thanks

I have the following in a codebehind file default.aspx.vb:

<WebMethod()> _
Public Shared Function GetStatisticData(ByVal userId As Integer) As JavaScriptSerializer
    Dim stats As JavaScriptSerializer = New JavaScriptSerializer()

    stats.Serialize(statBiz.GetAllSaleStatistics(userId))

    Return stats
End Function

And in default.aspx

opt.ajax({
    type: "POST",
    url: 'default.aspx/GetStatisticData',
    data: "{userId: 6601}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        console.log(data);
    },
    error: function (request, status, error, response) {
        console.log(error);
    }
});

But the method in the codebehind file does never get hit and i get this error from the console log:

SyntaxError: Unexpected token < in JSON at position 2
    at JSON.parse (<anonymous>)
    at n.parseJSON (jquery-1.12.4.min.js:11)
    at Xb (jquery-1.12.4.min.js:11)
    at y (jquery-1.12.4.min.js:11)
    at XMLHttpRequest.c (jquery-1.12.4.min.js:11)

Can sombody tell me what i am missing here?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim Button As System.Web.UI.WebControls.Button

    Dim x As Integer
    Dim y As Integer
    Dim name As Integer

    x += 10
    y += 10
    Label1.Text = x
    Label2.Text = y
    name = name + 1
    Button = New Button()
    Button.ID = "TextBox" & name
    Button.Style("Position") = "fixed"
    Button.Style("Top") = y & "px"
    Button.Style("Left") = x & "px"
    Panel1.Controls.Add(Button)
End Sub

I want you to constantly produce new buttons on the page.

This question already has an answer here:

I am at a loss here, here is my code in my Model

 public class Movie
    {
        public int Id { get; set; }
        public string Name { get; set; }

    }

here is the code in my controller

public class MoviesController : Controller
    {

        public ActionResult Random()
        {
            var movie = new Movie();
            movie.Name = "Kevin";
            return View();
        }
    }

here is the code in my view

@model Vidly.Models.Movie
@{
    ViewBag.Title = "Random";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>@Model.Name</h2>

Please help guys, I have no idea what I am doing wrong?

I run Visual Studio 2017 Enterprise as Administrator and select File > Open > Web Site > FTP Site. I log in to the site using an IP Address, start directory and a username and password in Passive mode. After the site loads, I right click the App_Code folder and select Add New Item, I select class and name of NewClass.cs. When I click add, I get an error dialog box that says

Cannot add the file 'C:\Users\LP\AppData\Local\Temp\l1w5g2.k.0ho\Class.cs' to the local cache. The system cannot find the path specified.

If I right click on the folder again and select Refresh folder it shows a file now called NewClass.cs. However, if I double click the file I get another error dialog box that says

Unable to get file 'NewClass.cs' from the Web server.

I cannot work on this website at all. I think I need to delete or clear the 'cache' but have no idea how to do that. The path mentioned above does not exist. Unsure how to make this project editable again.

I have a visual basic web site and in one of the pages, for some reason, when I view the codebehind, every reference to an element is underlined (using visual studio 2015) and gives me an " is not declared" message. This just started today. I have not made any changes to the code at all. Here is a sample of what I have:

In my pay_web.aspx:

    <div id="container">
    <section class="banner_media_full page_banner" role="banner" id="banner">
        <div class="row">
            <div id="banner_full">
                <h1>Get Started</h1>            
            </div>
        </div>
    </section>
    <article class="row" id="content">
        <div>
            <asp:Label ID="lblErrMsg" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>

and here is my code behind:

    Protected Sub Page_Load(sender As Object, e As EventArgs)
    Try
        Dim li As System.Web.UI.HtmlControls.HtmlGenericControl = DirectCast(Me.Page.Master.FindControl("liGS"), System.Web.UI.HtmlControls.HtmlGenericControl)
        li.Attributes.Add("class", "current-menu-item")
    Catch ex As Exception
        lblErrMsg.Text = "!" & ex.Message.ToString()
    End Try

The element lblErrMsg is undefined, as far as code behind is concerned.

I am at a complete loss. I can provide full page code if you want to see it.

Thanks for any suggestions. Jonathan

I am beginner in asp.net so may be I have stupid question, but I need some help. I have a model and controller MAIN, with read/write rules. I have a create action in MainController, and it works, but I need that one of the field be dropdown and it has options from another table of Department. I have searched answer but I have not get full answer. So if you can, help me. If need I will write codes. Thanks a lot.

I have a foreach loop creating CheckBoxes, causing them to all have the same ID. I've got some CSS but when you check any box it puts the css onto the first iteration, how do I add some dynamic ID sort of thing to only add the css to the selected box?

Loop:

@foreach (var item in Model.Where(p => p.UserTable.ID == ViewBag.UserTableID))
{
    <tr>
        <td>
            <div class="select">
                <input type="checkbox" id="select" name="" />
                <label for="select"></label>
            </div>

css:

.select {
width: 20px;
position: relative;
}

.select label {
    cursor: pointer;
    position: absolute;
    width: 20px;
    height: 20px;
    top: 0;
    left: 0;
    background: #eee;
    border: 1px solid #ddd;
}

    .select label:after {
        opacity: 0.2;
        content: '';
        position: absolute;
        width: 9px;
        height: 5.5px;
        background: transparent;
        top: 4.8px;
        left: 5.4px;
        border: 3px solid #333;
        border-top: none;
        border-right: none;
        transform: rotate(-45deg);
    }

.select label:hover::after {
opacity: 0.5;
}

.select input[type=checkbox]:checked + label:after {
opacity: 1;
}

I have a simple event handler:

    import axios from "axios";

export default function handleUpdate(ev: Event) {
    console.log("Handle update triggered.");
    let trigger: HTMLElement = <HTMLElement>ev.currentTarget;
    let endPoint: string = trigger.getAttribute("data-item-endpoint");
    let itemID = trigger.getAttribute("data-item-id");
    let inputEls: NodeListOf<HTMLInputElement> = <NodeListOf<HTMLInputElement>>document.querySelectorAll(`[data-item-id=${itemID}`);
    let updatedObj = buildObj(inputEls);

    axios.put(endPoint, updatedObj)
        .then((res) => {
            alert("Updated item");
        }).catch((ex) => {
            alert("Sorry, an error has been encountered.");
            console.log(ex);
        })
}


 function buildObj(inputEls: NodeListOf<HTMLElement>) : any {
    let obj: any = {};

    for(let i: number = 0; i <inputEls.length; i++) {
    const inputEl: HTMLElement = inputEls[i];
    const prop = (<HTMLInputElement>inputEl).name;
    let val = "";
    if (inputEl.hasAttribute("type") && inputEl.getAttribute("type").toLowerCase() == "checkbox") {
        val = (<HTMLInputElement>inputEl).checked ? "true" : "false";
    } else if (inputEl.hasAttribute("type") && inputEl.getAttribute("type").toLowerCase() == "file") {
        continue;
    } else {
        val = (<HTMLInputElement>inputEl).value;
    }
    obj[prop] = val;
}

return obj;

    }

The function is imported from a script:

    import SearchBar from "search_bar";
import handleUpdate from "./handleUpdate";

let searchBar = new SearchBar("editFilterContainer", "editTableContainer");

which is referenced in my layout file:

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Insurance Enrollment</title>
    @Styles.Render("~/Content/css")

</head>
<body>
    <div class="container-fluid">
        <header class="row mb-5">
            <div class="col-md-4"><h1>Insurance Midam Admin</h1></div>
            <div class="col-md-8">
                @RenderSection("links", required: false)
            </div>
        </header>
    </div>
    <div class="container">
        @RenderBody()
    </div>
</body>

</html>
<script src="~/Scripts/distr/main.js"></script>
<script src="~/Scripts/distr/admin.js"></script>
@RenderSection("scripts", required: false)

However, I whenever I attempt to attach the event to an HTML element (located in a View referencing the layout file), I receive a handleUpdate is undefined message (I have tried both with and without the parentheses).

    <option onclick="handleUpdate()"  value="true">Unenrolled</option>

Full View for Reference:

    @{Layout = "~/Views/Shared/_AdminLayout.cshtml";}
@model InsuranceMidAm.ViewModels.AdminEmployeeViewModel
@{
    ViewBag.Title = "Manage Eligible Employees";
}

@section links {
    <nav id="adminNav">
        <ul>
            <li><a href="~/Admin/">Admin Home</a></li>
            <li><a href="~/Admin/agreements">Agreements</a></li>
            <li><a href="~/Admin/employees">Employees</a></li>
            <li><a href="~/Admin/plans">Plans</a></li>
            <li><a href="~/Admin/resources">Resources</a></li>
        </ul>
    </nav>

}
<h1>Manage Eligible Employees</h1>

<div data-filter-endpoint="/Admin/EditValidations" id="editFilterContainer" class="form-row">
    <div class="form-group col-sm-4">
        <label>Page: </label>
        <select id="pageNumber" class="form-control" name="pageNumber">
            @for (int i = 1; i <= Model.pagesAvailable; i++)
            {
                if (i == Model.currentPage)
                {
                    <option selected value="@i">@i</option>
                }
                else
                {
                    <option value="@i">@i</option>
                }
            }
        </select>
    </div>
    <div class="form-group col-sm-4">
        <label>Search (Last Name)</label>
        <input class="form-control" oninput="resetPage()" type="text" name="nameSearch" />
    </div>
    <div class="form-group col-sm-4">
        <label>Enrollment Status: </label>
        <select oninput="resetPage()" class="form-control" name="unenrolledOnly">
            <option value="false">All</option>
            <option onclick="handleUpdate()"  value="true">Unenrolled</option>
        </select>

    </div>
</div>

@{Html.RenderPartial("_EditValidationPartial", Model);}
@section scripts {
    <script>function resetPage() {
    document.getElementById("pageNumber").selectedIndex = 0

}</script>
    }

I am using webpack as my bundler:

    const path = require("path");
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    context: path.join(__dirname, "Scripts/src/"),

    entry: {
        main: "main.ts",
        admin: "admin.ts"
    },

    output: {
        filename: "[name].js",
        path: path.resolve(__dirname, "Scripts/distr")
    },
    resolve: {
        extensions: ['.js', '.jsx', '.ts'],
        modules: ["node_modules", "src"]
    },

    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'awesome-typescript-loader'
            }
        ]
    },

    plugins: [
        new CleanWebpackPlugin("Scripts/distr/*", { exclude: "assets/*" }),

    ]

} 

I am not experienced with using ES6 features with the Razor View Engine.

What am I missing? Any help would be appreciated.

Thanks.

I'm using Knockout to create a dynamic form. I have a table and the user can add new rows to the table via a button click. My Bootstrap selectpicker appears in the first row, but not in the new rows added by the button click. Here's a screenshot:

enter image description here

My research indicates that when the Bootstrap select is added dynamically (as it is in this case) it needs to be rendered each time. It can be rendered like so:

$('.selectpicker').selectpicker('render');

This seems to be the case because I have tried the render in several places in my code. However, despite several hours of tinkering, I have not been able to get it to render properly on every button click. Sometimes it renders two or more select pickers on each row, for example. Here is my full Razor page code:

@model Birder2.ViewModels.CreateObservationViewModel
@using Microsoft.AspNetCore.Identity
@inject UserManager<ApplicationUser> UserManager
@using Newtonsoft.Json
@{
    string data = JsonConvert.SerializeObject(Model);
}
@section scripts{
    <script src="~/js/knockout-3.4.2.js"></script>
    <script src="~/js/knockout.mapping-latest.js"></script>
    <script src="~/js/createobservationviewmodel.js"></script>
    <script type="text/javascript">
        var createObservationViewModel = new CreateObservationViewModel(@Html.Raw(data));
        createObservationViewModel.Observation.LocationLatitude = @UserManager.GetUserAsync(User).Result.DefaultLocationLatitude
            createObservationViewModel.Observation.LocationLongitude = @UserManager.GetUserAsync(User).Result.DefaultLocationLongitude
            ko.applyBindings(createObservationViewModel);
            $(select).selectpicker('render');
    </script>
}
<h2>Create an observation</h2>
<form>
    <div class="form-group">
        @* change to Partial View like Manage Index *@
        <span class="control-label" name="MessageToClient" data-bind="text: MessageToClient" />
    </div>

    <div class="form-group">
        <label class="col-sm-2 control-label" for="Observation.ObservationId">Id:</label>
        <div class="col-sm-10">
            <span class="form-control" name="Obervation.ObservationId" data-bind="text: Observation.ObservationId@*, event: {change: flagSalesOrderAsEdited}*@" />
        </div>
    </div>

    <div class="form-group">
        <label class="col-sm-2 control-label" for="Observation.ObservationId">Date:</label>
        <div class="col-sm-10">
            <input class="form-control" data-bind="datePicker : Observation.ObservationDateTime" type="date" />
        </div>
    </div>
    <div class="form-group">
        <input class="form-control" name="Observation.LocationLatitude" data-bind="value: Observation.LocationLatitude" />
        <input class="form-control" name="Observation.LocationLongitude" data-bind="value: Observation.LocationLongitude" />
    </div>
    <div class="form-group" spellcheck="true">
        <label class="col-sm-2 control-label" for="Observation.Note">Note:</label>
        <div class="col-sm-10">
            <input class="form-control" name="Observation.Note" data-bind="value: Observation.Note" />
        </div>
    </div>

    <hr />
    <hr />

    <table class="table table-striped">
        <tr>
            <th class="text-right">Quantity</th>
            <th class="text-right">Bird</th>
            <th><button class="btn btn-info btn-xs" data-bind="click: addObservedSpecies">Add</button></th>
        </tr>
        <tbody data-bind="foreach: ObservedSpecies">
            <tr>
                <td class="form-group"><input name="ObservedSpecies.Quantity" class="form-control input-sm text-right" data-bind="@*attr: {'id': 'Quantity_' + $index()},*@ value: Quantity@*, event: {change: flagSalesOrderItemAsEdited}*@" /></td>
                <td class="form-group">
                    @Html.DropDownListFor(m => m.Observation.BirdId,
                        new SelectList(Model.Birds, "BirdId", "EnglishName"),
                        new
                        {
                        @class = "form-control selectpicker show-tick",
                        data_bind = "value: BirdId",
                        title = "Choose a bird",
                        data_live_search = "true",
                        data_show_subtext = "true"
                        })
                </td>
                <td class="form-group">delete</td>               
            </tr>
        </tbody>
    </table>
</form>

Can anyone offer any help on how I can render each selectpicker?

Update:

If I remove the bootstrap select, leaving it as an ordinary select list, everything works as expected. So it is just a matter of getting the Bootstrap select picker to render properly.

I am new to episerver CMS. I have installed episerver cms alloy sample site. Also I found the code to show the navigation menu on the "_Root.cshtml".

   @Html.RenderEPiServerQuickNavigator()

So I have used same code on my new website to render the navigation menu

 <nav id="topnavigation">         
        @Html.RenderEPiServerQuickNavigator()       
    </nav>

The Navigation is not showing on my website. Can any one help me to implement navigation menu on my episerver cms website?