ASP.NET

125K

Solutions

28K

Contributors

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 have a button to delete checked items in a list.
I want to display a confirmation prompt before continuing with the delete routine.
I'm not certain how to do this.
I've tried with some code I found online that has a javascript function in the aspx code, but it doesn't seem to process that script.
0
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>";
                            }
                            else
                            {
                                

Open in new window

0
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?
0
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.
0
I'm creating a simple form in asp.net.
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 asp.net, 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)
0
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.
https://localhost:44312/
Then I create a controller called ApplicantsController.
When I try to navigate to,
https://localhost:44312/Applicants
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

0
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:

<httpProtocol>
      <customHeaders>
        <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="*" />
      </customHeaders>
    </httpProtocol>

Open in new window


Any ideas please thanks.
1
Hi,
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 https://js.devexpress.com/Demos/WidgetsGallery/Demo/DataGrid/Overview/NetCore/Light/ 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 asp.net core, since I am already develop in windows forms.

best regards
0
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 :)
0
Hi,
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?
0
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 asp.net)

aspx:
 <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>
                        <NoRecordsTemplate>
                            Setup / PDI items...
                        </NoRecordsTemplate>
                        <Columns>
                             

Open in new window

0
Find always returns null when trying to find control on asp.net 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#
Isaac

 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");
                            }
                            else
                            {
                                txt.Attributes.Remove("required");
                            }
         

Open in new window

0
Hello,
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.
        }
0
Following on from this question
https://www.experts-exchange.com/questions/29143196/Float-array-in-c-when-passed-to-JS-it's-in-wrong-order.html?headerLink=workspace_answered_questions

I now need to
call the following

 $.ajax({
                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
imageDataArray[x][y]

Open in new window

to get the value at that position

How would i do this in Js/Jquery?
0
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,
Isaac

<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"/> 
                  </div>
                </div>            



 <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);
           return;
       }
</script>        

Open in new window

0
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.
0
I have an asp.net 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(){
    $("sidemenu").toggle("slow");
}

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 asp.net web forms.


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

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

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

</asp:Content>
0
This question is for someone who has learned asp.net 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?
0
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... http://www.enflow.com/CC/P1/P3.aspx   - - 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="System.data.OleDb" %>
<%@ import Namespace="System.Web.UI.WebControls" %>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    Sub Page_Load(sender As Object, e As EventArgs)
        'a
    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

0
I have a few submit buttons on a asp.net 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 () {
                $('#Process').on('click',
                    function (event) {
                        $('.submit-button').attr('disabled', true);
                        $('#Process').submit();


                    });
                $('#Issue').on('click',
                    function (event) {
                        $('.submit-button').attr('disabled', true)
                        $('#Issue').submit();


                    });

            });

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,
Bonnie
0
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)
e1.png
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?
0
I am using ASP.NET with an MVC 5 project and entity framework. I want to remove the required attribute that is created implicitly based on the SQL database field. I keep getting entity validation errors on the EMailAddress2 field in the form. I tried these two things among others.

1)  I added @{ Html.EnableClientValidation(false);} to the code in the create view for that div, but that did not resolve the issue.
2) I added DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; to the global.asax.

Create view code:

<h2>Create</h2>

@{ Html.EnableClientValidation(false);}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>user</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.CustomerName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
            </div>
        </div>

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

Open in new window

0
Using Visual Studio 2017 Community edition...

Trying to design aspx web page using asp.net tool table layout panel tool out of toolbox for web apps...

Toolbox controls are disabled for tablelayoutpanel and other similar asp.net tools...

Attached is file working on... Sample.aspx
Sample.aspx
0
Hi,
 I Have two repeaters one nested inside the other. During the page load in vb code behind I need to be able to access the button1,button2, and button3 visible property inside the child repeater . I want to be able to make these buttons visible or invisible based on users variables. Right now I can't figure out how to access those properties I the page load, Please help.  I pasted the Page and its code behind below.

<%@ Page Title="" Language="VB" MasterPageFile="~/EEMainMaster.master" AutoEventWireup="false" CodeFile="testrepeator.aspx.vb" Inherits="testrepeator" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script type="text/javascript">

    $("body").on("click", "[src*=plus]", function () {

        $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")

        $(this).attr("src", "images/minus.png");

    });

    $("body").on("click", "[src*=minus]", function () {

        $(this).attr("src", "images/plus.png");

        $(this).closest("tr").next().remove();

    });

</script>
    <H1 style="text-align:center" >Communications Committee Activities</H1>
    <asp:Repeater ID="rptCustomers" runat="server" OnItemDataBound="OnItemDataBound">

    <HeaderTemplate>

        <table style="width: 100%"class="Grid" cellspacing="0" …
0
I have two lists of alphanumerics provided below, How could I ensure that they are sorted based on our regular expression i.e. [Z-A, 9-0] and [0-9, A-Z] . In list two blank should come first as mentioned in List-2.

List-1
T
S
IApplicationCache
D
A
10
9
8
7

Open in new window


List-2
""
1
2
34
56
A
B

Z

Open in new window

0

ASP.NET

125K

Solutions

28K

Contributors

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