The successor to Active Server Pages, ASP.NET websites utilize the .NET framework to produce dynamic, data and content-driven web applications and services. ASP.NET code can be written using any .NET supported language. As of 2009, ASP.NET can also apply the Model-View-Controller (MVC) pattern to web applications

Share tech news, updates, or what's on your mind.

Sign up to Post

I need to use HTML encode to filter/scrub some data being read by my SqlDataReader object. Trying to prevent an XSS attack. I've never used HTML encode before but I need to apply it to code that looks like the following:

                        oReader = oCmd.ExecuteReader();

                    if (oReader.HasRows == true)
                        int iLastID = 0;
                        decimal total = 0;

                        while (oReader.Read())
                            if (iLastID != oReader.GetInt32(oReader.GetOrdinal("checktypeid_fk")))
                                sTableDetail += "<tr>";
                                sTableDetail += "<TD>" + oReader.GetValue(oReader.GetOrdinal("Description")).ToString() + "</TD>";
                                sTableDetail += "<TD>" + oReader.GetValue(oReader.GetOrdinal("Quantity")).ToString() + "</TD>";
                                sTableDetail += "<TD align=right>$" + oReader.GetValue(oReader.GetOrdinal("Amount")).ToString() + "</TD>";
                                sTableDetail += "<TD align=right>$" + Convert.ToString(Convert.ToDouble(oReader.GetValue(oReader.GetOrdinal("Amount"))) * Convert.ToDouble(oReader.GetValue(oReader.GetOrdinal("Quantity")))) + "</TD></TR>";

Open in new window

I have an ASP.NET MVC application built database first and Entity Framework.
The Sql Server database has a table named Applicant that has a foreign key to a reference table called ApplicantType_Ref.
When I create the scaffolding, the resulting model, Applicants.cs has the foreign key, ApplicantTypeId as a property:
public int? ApplicantTypeId { get; set; }

Open in new window

When I run the application and create a new applicant, the resulting view shows me, as expected, a drop down for the Applicant Type Id.
What I need to see instead is a drop down for the Applicant Type in the same row of the table as the Applicant Type Id.
How do I do that?
Do I change something in the Applicant.cs model before creating the controller?
I do see a property for the ApplicantType_Ref table itself:
public ApplicantTypeRef ApplicantType { get; set; }

Open in new window

Do I use that property in the view or the controller, replacing the other property, ?
In other words, how do I get the drop down box to show the actual applicant type instead of the list of ApplicantTypeId primary keys?
On page load, I'm going to grab details of a user's assignments, based on the user coming to the site.
I'm going to populate a checkedlistbox with just a reference ID and associated title.

However, when they click on an item, I want to show the further details based upon that reference ID.

Originally I was going to create a list, and add reference to all of the details there, but I believe that maybe cookies might serve me better here - although I'm not very familiar how to use them properly.

Can someone provide some guidance?
I'd love to have some ability to search a cached table based on the ID selected, and retrieve the details that way, rather than making another call to the databse.
I have an web forms website. I have two aspx pages ( say abc.aspx and xyz.aspx)   right now in my project. Right now, I have a navigation menu , to go to each of these pages , but instead of that I want to combine the two navigation item, into one had inside that page, I want to have tabs so that i can switch between the two aspx pages.

I looked into asp multi view tutorial (see below).

one thing  I am wondering about is , if I have this asp: multiview implemented, then I will have to combine both of the abc.aspx.cs and xyz.aspx.cs file into one cs file or
combine both back end code into file. is there a way, instead of doing that I can keep the two files and separate and load just the content based on which tab is clicked?

<asp:MultiView     ID="MultiView1"  runat="server"   ActiveViewIndex="0"  >
   <asp:View ID="Tab1" runat="server"  >                              TAB VIEW 1             </asp:View>
    <asp:View ID="Tab2" runat="server">                               TAB VIEW 2             </asp:View>

I'm using AJAX AjaxFileUpload.

My symptoms are the OnUploadComplete event is running twice when only 1 file is selected. The second time I receive an error as follows:

  Message=Could not find a part of the path 'C:\WINDOWS\TEMP\_AjaxFileUpload\974AB760-DCFE-2E04-E0D9-A0EE7E73221A\IMG_3001.JPG.tmp'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
   at AjaxControlToolkit.AjaxFileUpload.SaveAs(String fileName)
   at Graphic.AjaxFileUpload1_UploadComplete(Object sender, AjaxFileUploadEventArgs e) in C:\inetpub\ClientWebs\AJAX File Upload Test\Graphic.aspx.vb:line 13
   at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
   at AjaxControlToolkit.AjaxFileUpload.UploadRequestProcessor.XhrDone(String fileId)
   at AjaxControlToolkit.AjaxFileUpload.UploadRequestProcessor.ProcessRequest()

The AjaxFileUpload event results in this error because this event is entered a 2nd time for reasons I do not, as yet, understand.

My aspx page is as follows:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Graphic.aspx.vb" Inherits="Graphic" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>

<!DOCTYPE html>


Open in new window

I'm creating a simple form in
On page load, I want to display the user's name (I'll get to that later if I can't figure it out )
Next I want to retrieve a list of elements from a SQL table that belong to this user.
If there are any results returned, I want to get a total and display a label that says "You have X items" and then show a checked listbox with the items.
If there are no results, no list would be displayed and a message stating that they have no items.

I can handle the  logic for displaying everything, but it's been so terribly long since I've done any development in, that I don't really know where to begin to make that SQL connection and pull back results.
I would need to pass credentials because the user's account won't have permissions to read the data.
But the table layout will have a field called Owner that would be equivalent to their user ID that I'm returning from the windows login identity.

If someone could help me get started, I think I can carry this on to completion, as presumably it will come back to me... (I hope)
Hi All,
I am using most secured application and i couldn't share or upload any files other than .txt.
I am using VS 2013 , C#. My requirement is
1)The application should be set to disconnect a user’s session upon log on from a different location.
2)Also If user login from same server in two different browsers by hacking the same session , then i need to capture the time of login , IP address and browser name and login ID

Please find the global.asax.cs and web.config

Kind regards,
I've created an Asp.Net core MVC application, database first. .NETCore.App (2.1).
It is the first MVC Core app that I've created.
When I run the application with IIS Express, it loads in the browser correctly.
Then I create a controller called ApplicantsController.
When I try to navigate to,
I get the following error:
InvalidOperationException: Unable to resolve service for type 'SalaryCalculator.Models.Salary_CalculatorContext' while attempting to activate 'SalaryCalculator.Controllers.ApplicantsController'.

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

Here is the Startup.cs class:

public class Startup
        public Startup(IConfiguration configuration)
            Configuration = configuration;

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
            services.Configure<CookiePolicyOptions>(options =>
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;

Open in new window

Access to XMLHttpRequest at 'http://someURL' from origin 'http://someURL' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.

This is a call to a REST API controller action method. I enabled CORS on the top of controller like below:
[EnableCors(origins: "*", headers: "*", methods: "*")]
 public class TestController : ApiController

Open in new window

Also in the web.config:

        <add name="Access-Control-Allow-Credentials" value="true" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE" />
		<add name="Access-Control-Allow-Origin" value="*" />

Open in new window

Any ideas please thanks.
I am using ASP.NET MVC 5 with entity framework. I have an existing SQL database that houses a table with a path and name for an attachment (Attachment) that links to another table (Meeting). I want the details view of the Meeting to show the name of the attachment and a link to download the attachment. The attachments are stored on a server on the same network. The attachments are not housed in SQL. I will also want to update the create view to create an attachment but I want to tackle one thing at a time.

Sidenote: This project was created using Entity Framework scaffolding so most of the code is default created from the scaffolding.

Meeting Details View

@model CRM.Models.Meeting

    ViewBag.Title = "Details";


<div id="MeetingDetails">
    <hr />
    <dl class="dl-horizontal">
            @Html.DisplayNameFor(model => model.InteractionDate)

            @Html.DisplayFor(model => model.InteractionDate)
        <br />
            @Html.DisplayNameFor(model => model.Notes)

            @Html.DisplayFor(model => model.Notes)
        <p />

            @Html.DisplayNameFor(model => model.CustomerCallDecisionedBy)

            @Html.DisplayFor(model => model.CustomerCallDecisionedBy)
        <br />
            @Html.DisplayNameFor(model => 

Open in new window

I always developed in windows forms. However now I came up with a litle project for the web. I'm using Devexpress components, however this is still a bit confusing for me. For example, the following link shows several examples. From what I understand I can choose one of these frameworks presented or even the Asp.Net core, to develop on Api Devexpress. I would like to know if this is correct, and what would be the best choice. For me it might be easier core, since I am already develop in windows forms.

best regards
Change MasterPage depending on URL. Is  this possible.

I have 2 departments at work that both use the same site I built but they want to call it by different names. So when I built it back in 2014 I published it twice with two different titles and different name in the master page. So what I want to do (if possible) is put 2 urls to the same site but depending what url they use will affect the masterpage, eg wether the title will say Dept A or Dept B and change the label at the top of the master page to say Dept A or Dept B, or would it be any easier to just make 2 different Master pages and somehow load a different one depending on url.
I have no idea how to go about this so any ideas are greatly appreciated :)
I have an ASP.NET MVC Core 2.1.1 project running in Visual Studio 2019.
Since I have already created a database, I want to connect the application to the existing database with database-first development.
From the Visual Studio, Package Manager Console, I put in:

Scaffold-DbContext "server=ServerName;Database=DbName; Trusted_Connection=true; Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

That gives me the following error:
The EF Core tools version '2.1.1-rtm-30846' is older than that of the runtime '2.1.8-servicing-32085'. Update the tools for the latest features and bug fixes.
Unable to find provider assembly with name server=ServerName. Ensure the specified name is correct and is referenced by the project.

I got the name, ServerName, directly from the Visual Studio connection properties:
Data Source=ServerName; Initial Catalog=DbName; Integrated Security=True

Is there something different I should put for ServerName?
In my Web Form, I have a TreeView and a DataGrid. When a user selects a node from the tree, an SQL query retrieves related values from the Database and populates a row in the grid. The user will be selecting multiple nodes, so I need the rows appended to grid, not overwriting previous ones. Also need to be able to delete a row from the grid if the user chooses. I have been cobbling together bits of code from many forums to use session variables, but cant seem to get it to work. As soon as I code anything relating to a session variable the grid stops populating. If I remove the "session stuff" , then the grid works fine, but each row gets overwritten with the next node selection.  My code is below. Thanks in advance for any help. (I am still fairly new to

 <telerik:RadGrid ID="RadGrid1" runat="server" 
                         AutoGenerateColumns="False"   Skin="Telerik" OnDeleteCommand="RadGrid1_DeleteCommand"  AutoPostBack="true"> 
                        <GroupingSettings CollapseAllTooltip="Collapse all groups"></GroupingSettings>
                        <MasterTableView  DataKeyNames="ID" HorizontalAlign="NotSet" AutoGenerateColumns="False">
                        <FooterStyle CssClass="gridFooter"></FooterStyle>
                            Setup / PDI items...

Open in new window

Find always returns null when trying to find control on page.

I'm pulling valid names from a list which should find the control which
exists in the page.

Can someone lead me in the right direction.  I am using vs 2013 and c#

 private void LoadForm(List<ProviderFields> providerList)
            foreach (ProviderFields req in providerList)
                // taget div for plan
                  Control ctrl = Page.FindControl("div" + req.aspName);
                // set visible to true if we found it.
                if (ctrl != null)
                    //set div to visible
                    ctrl.Visible = true;

                    // set label to proper text
                    Label lbl = (Label)Page.FindControl("lbl" + req.aspName);
                    lbl.Text = req.displayName;
                    switch (req.aspType)
                        case "txt":
                            TextBox txt = (TextBox)Page.FindControl("txt" + req.aspName);
                            if (req.fieldRequired)
                                lbl.Text = req.displayName + " " + "*";
                                txt.Attributes.Add("required", "required");

Open in new window

Anything incorrect below as i am getting only single field rather then 3 in the datareader. I am just getting StudentID field value only.

SqlCommand getStudent = InitiateDatabaseCommand();

            getStudent.Parameters.Add("@StudentId", SqlDbType.Int);
            getStudent.Parameters["@StudentId"].Value = 1;
            getStudent.CommandText = "Select * From Student  r where r.StudentID=@StudentId AND r.Name like '%R%'";

            SqlDataReader dr = comm.ExecuteReader();

        while (dr.Read()){

           //filling the studentinfo data model object here.
Following on from this question's-in-wrong-order.html?headerLink=workspace_answered_questions

I now need to
call the following

                type: "POST",
                url: "@Url.Action("CameraChange", "Home")",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                   imageDataArray = response.DataArray;

Open in new window

However I've no idea how to convert to returned string
[[273.7,273.8,273.8,274.6,274.6,274,274,274.3,274........ ]]

Open in new window

to the JS object: imageDataArray

In the othe question i used @HTML.RAW, which works great and i can then access the data like

Open in new window

to get the value at that position

How would i do this in Js/Jquery?
I am trying to validate the presence and pattern of a field defined in an asp. net page.
The presence of the field works but when I enter the telephone number in the
field for pattern matching, it does not work. I get the error message.

Please advise,

<div visible="true" id="divTelephoneNumber" runat="server">
                  <div class="col-xs-12 col-md-8 col-sm-10 col-lg-6 nill">
					<asp:Label ID="lblTelephoneNumber" runat="server" AssociatedControlID="txtTelephoneNumber" Text="Telephone number *" CssClass="control-label" />
                      <br />
					<asp:TextBox ID="txtTelephoneNumber" runat="server" CssClass="form-control" MaxLength="20" aria-label="Telephone number" ></asp:TextBox>
					<span class="required"></span>
                    <asp:CustomValidator id="rfVTN" runat="server" ControlToValidate="txtTelephoneNumber"  ValidateEmptyText="true" ErrorMessage="Telephone Number is a required field. nnn-nnn-nnnn " ClientValidationFunction="ValidateTelephone"/> 

 <script type="text/javascript">
       function ValidateTelephone(sender, args) {
           var compare = RegExp("/^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/");
           args.IsValid = compare.test(args.Value);

Open in new window

Web Deploy stuck

I am currently migrating one of our web servers using Web Deploy. The command used is shown below.

msdeploy.exe -verb:sync -source:webServer,computername=computername -dest:webServer -enableLink:AppPoolExtension >log.txt

Open in new window

The above command worked as expected for a previous migration, bur during the current migration it seems to hang.
I've noticed the folder structures are created successfully, the sites and application are created, but no files were copied over.

I then tried the following command with the same results
msdeploy.exe -verb:sync -source:webServer,computername=sp-web02 -dest:auto -enableLink:AppPoolExtension >log.txt

Open in new window

The migration seems to be stuck at "Updating applicationDefaults"  I've attached the log.  log.txt

It is also important to note that on the source server the bindings defines the allocated IP address.
I have an web forms website with master page and few other pages.

In master page, i have <asp:ContentPlaceHolder ID=“Placeholder1” runat=“server”></asp:ContentPlaceHolder> , where the content of the child pages are loaded.

one of the page is default.aspx ,, as such

<asp:Content runat=“server” ID=“content1” ContentPlaceHolderID=“Placeholder1”></asp:Content>

I want to change default.aspx , such that I have a side menu column and a content column. Aslo I have a anchor tag. I wrote a javascript/jquery function as such on documen t ready

$("#togglemenu").on(click, function(){

the toggle works, but in the main content section , i have a table and can increase the size of the rows displayed in the table, when I change the pagenumber or change the number of items displayed in the table, the page refreshes and it doesn't maintain what state the sidemenu was in . I.e even if the menu was hidden, when i change the page number, the page refreshes and side menu appears . I want it to be hidden , if the user had hidden the menu and then changed the page number.

how can i achieve this in web forms.

<asp:Content runat=“server” ID=“content1” ContentPlaceHolderID=“Placeholder1”>

<a >  <span id="togglemenu" > Hide menu </span></a>
<div id="sidemenu">

<div id="main content"> </div>

This question is for someone who has learned core.

I know there’s a lot of references like Microsoft site, web tutorials, YouTube... etc.

But as far as books go, I searched Amazon for ASP.NET Core books. There are many books.

In your opinion which is a great book to start with that you recommend?

I use above codes to upload a file. but if I want to add a parameter from <input type="text" id="firstname"> to ajax like below. How can I do that? Basically, I upload the image but I also want to update the database behind.

type: "POST",
           url: '/Home/Upload',
           data: formData, document.getelementid("firstname").value,
           dataType: 'json',
           contentType: false,
Cost Of Converting THIS...

ASP.NET Web Form in Table layout (with atrocious CSS text/css)  to efficient DIV layout + CSS ??

   1. I built this but used VStudio verbose Jurassic table layout style and client wants concise DIV layout... so i need to have someone help me convert it...

   2. Here is link to my in progress ASP.Net web form...   - - minus (VB code and Validation Code)

   3. See source code for this...

<%@ Page Language="VB" AutoEventWireup="false" debug="true" %>
<%@ import Namespace="System" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<%@ import Namespace="" %>
<%@ import Namespace="System.Web.UI.WebControls" %>

<%@ Register assembly="System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" namespace="System.Web.UI.WebControls" tagprefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<script runat="server">
    Sub Page_Load(sender As Object, e As EventArgs)
    End Sub

    Protected Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs)

    End Sub

    Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs)

    End Sub

    Protected Sub Address0_TextChanged(sender As Object, e As EventArgs)

    End Sub

    Protected Sub Month_TextChanged(sender As Object, e As EventArgs)

    End Sub

Open in new window

I have a few submit buttons on a core 2.1 page and users are clicking them a few times, thus submitting the form repeatedly.   I have tried jquery and javascript to disable the buttons on document.ready and onclick, but when I do that, the form data does not post.  It takes at least 5 seconds for the form to post which is why they are clicking away...
<input type="submit" class="btn btn-success" value="Process Batch Ticket" name="submit" asp-page-handler="SubmitIssue" id="Process"/>

Open in new window

When the button is clicked, it posts to a task:
public async Task OnPostSubmitIssue(string jobNumber, string warehouse, string status)

Open in new window

I have tried  having the task check a variable and only run when the variable is true, but when the user clicks the button again, it returns them to a blank model, while they usually get the same page with the submission results shown, so that is not working.

I have seen some posts about onclick vs. onclient click, but have not been able to figure out how to make those help.

I thought the jquery below would work, but it doesn't:
<script type="text/javascript">

            $(document).ready(function () {
                    function (event) {
                        $('.submit-button').attr('disabled', true);

                    function (event) {
                        $('.submit-button').attr('disabled', true)



Open in new window

Does anyone know which way I should keep trying to pursue?  I feel like I am going in circles for something that I wish was just built in with a switch.  Doesn't everyone want disable after first click at some point?

Thanks for any help,
I'm working on a Windows Forms project and it calls Web Services. This is how the project is setup (my new job)

1. The Windows Forms solution
2. Web Services solution
3. Windows Forms solution has references to the Web Services . Screenshot below (not the best naming convention, I know)
4. I downloaded Fiddler to see if I can see what Web Services method is being called. I see some logging but not Web Services.

Anyway I can see  which web services method is being called?






The successor to Active Server Pages, ASP.NET websites utilize the .NET framework to produce dynamic, data and content-driven web applications and services. ASP.NET code can be written using any .NET supported language. As of 2009, ASP.NET can also apply the Model-View-Controller (MVC) pattern to web applications