I have the following code in a button click method that goes through the rows of a GridView. ServiceFormQuestionTypeIDHF is a HiddenField.

The first time through the foreach statement the value of sfqtIdINT is 10 and the value of sfqtIdSTR is "10" yet the if statement is true. Now the value I am expecting for the HiddenField.ToInt() is 1.

I can confirm that the rest of the foreach statement and the rest of the if statements display the wrong value in sfqtIdSTR and sfqtIdINT but the behaviour of the if statement is the value I am expecting from that row in the GridView. In other words the HiddenField has the right value but displays the wrong value.

I can see no reason for this. Can anyone provide a reason for this?

 foreach (TableRow tr in FormGV.Rows)
 {
     HiddenField ServiceFormQuestionTypeIDHF = (HiddenField) tr.FindControl("ServiceFormQuestionTypeIDHF");
     int sfqtIdINT = ServiceFormQuestionTypeIDHF.Value.ToInt();
     string sfqtIdSTR = ServiceFormQuestionTypeIDHF.Value;                       
     if ((ServiceFormQuestionTypeIDHF.Value.ToInt() == 1 )||
                        (ServiceFormQuestionTypeIDHF.Value.ToInt() == 2))
     { .......
       .......
     }

I have created gridview with textbox and button. In textbox I can enter the required number for number of columns I want to add to the grid. The column header should change like t1, t2... Here is my code.

protected void Page_Load(object sender, EventArgs e)
{
 if (!IsPostBack)
    {
        griddisplay();
    }
}
public void griddisplay()
{
    con.Open();
    SqlCommand cmd = new SqlCommand("SELECT * FROM testclientinfo", con);
    SqlDataReader dr = cmd.ExecuteReader();
    GridView1.DataSource = dr;
    GridView1.DataBind();
    con.Close();
}

protected void btnadd_Click(object sender, EventArgs e)
{
    int num;
    num = Convert.ToInt32(txtnumber.Text.Trim());
    for (int i = 1; i <= num; i++)
    {


        string name = "t";
        name = string.Concat(name, i);
        BoundField test = new BoundField();
        test.HeaderText = name;
        GridView1.Columns.Add(test);

    }
}

Issues are 1.columns are added for second click on add button, when I enter number in textbox and click on add button columns are not added. 2. For example if I enter 2 in textbox t1 & t2 columns are added, again when click on add column header should be t3 & t4 but again t1 and t2 are being added. Please help.

I'm fairly new to mvc, and have started learning asp.net mvc 5 and django

I want to create an application where the user can create a new view at runtime. So lets say I create a feature in the web app for a user to add a new page where they can fill out a form, say the title maybe text, or fields they want to display on the view, and when the user saves it that info gets saved to the db and creates a new view.

My questions are:

  • can you create dynamic views at runtime?

  • how do you create the proper url to route to that new page?

  • if the 1st two are possible can you use a model or viewModel to then display the content from the db for that page?

Any advice on if this can be done would be appreciated. Thanks

I have a requirement to bind folders and files to the treeview based on table data from data base, i tried lot of solution but failed to meet specific requirement.

Here is what im looking

Top foldersTable from database

I have found one sample code and tried to achieve this

`

 private void PopulateTreeview(DataTable dtFolders)
    {
        tvVendors.Nodes.Clear();
        HierarchyTrees hierarchyTrees = new HierarchyTrees();
        HierarchyTrees.HTree objHTree = null;
                    if (dtFolders.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dtFolders.Rows)
                        {
                            objHTree = new HierarchyTrees.HTree();

                            objHTree.LevelDepth = int.Parse(dr["level"].ToString());
                            objHTree.NodeID = int.Parse(dr["folderid"].ToString());
                            objHTree.UnderParent = int.Parse(dr["parentid"].ToString());
                            objHTree.FIleName=dr["filename"].ToString();
                            objHTree.FilePath=dr["filepath"].ToString();
                            hierarchyTrees.Add(objHTree);
                        }

                    }
        //Iterate through Collections.
        foreach (HierarchyTrees.HTree hTree in hierarchyTrees)
        {
            //Filter the collection HierarchyTrees based on 
            //Iteration as per object Htree Parent ID 
            HierarchyTrees.HTree parentNode = hierarchyTrees.Find
            (delegate(HierarchyTrees.HTree vendor)
            { return vendor.NodeID == hTree.UnderParent; });
            //If parent node has child then populate the leaf node.
            if (parentNode != null)
            {
                foreach (TreeNode tn in tvVendors.Nodes)
                {
                    //If single child then match Node ID with Parent ID
                    if (tn.Value == parentNode.NodeID.ToString())
                    {   
                        tn.ChildNodes.Add(new TreeNode
                        (hTree.NodeDescription.ToString(), hTree.NodeID.ToString()));
                    }

                    //If Node has multiple child ,
                    //recursively traverse through end child or leaf node.
                    if (tn.ChildNodes.Count > 0)
                    {
                        foreach (TreeNode ctn in tn.ChildNodes)
                        {
                            RecursiveChild(ctn, parentNode.NodeID.ToString(), hTree);
                        }
                    }
                }
            }
            //Else add all Node at first level 
            else
            {
                tvVendors.Nodes.Add(new TreeNode
                (hTree.NodeDescription, hTree.NodeID.ToString()));
            }
        }
        tvVendors.ExpandAll();
    }

    public void RecursiveChild(TreeNode tn, string searchValue, HierarchyTrees.HTree hTree)
    {
        if (tn.Value == searchValue)
        {
            tn.ChildNodes.Add(new TreeNode
            (hTree.NodeDescription.ToString(), hTree.NodeID.ToString()));
        }
        if (tn.ChildNodes.Count > 0)
        {
            foreach (TreeNode ctn in tn.ChildNodes)
            {
                RecursiveChild(ctn, searchValue, hTree);
            }
        }
    }

Problem: I'm not able to bind file name to leaf node, if folder does not have any subfolder. bind the files. or if folder has subfolder and file both.bind both at same level. if folder is empty, it has nothing just bind it blank.

Could please test the code provide some solution`

I have an Index action from Home Controller that send form details to Index Action in Result controller using this snippet below:

@using (Html.BeginForm("Index", "Result", new { ViewBag.ReturnUrl }, FormMethod.Get, new { role = "form" }))
{ }

The Url generated when page loads in Result page look like this:

https://localhost/WebApp/result?Prop1=wayne+in&Prop2=1

I'm using this route to create clean URL:

routes.MapRoute(
       name: "ResultPage",
       url: "result/{Prop1}/{Prop2}",
       defaults: new
       {
          controller = "Result",
          action = "Index",
          Type = UrlParameter.Optional
       }
      );

When I enter the clean URL https://localhost/WebApp/result/Quitman%20GA/1 directly in browser page loads correctly.

If I'm trying to create these clean URLs directly from the form parameters sent to the Result Index page, is this something achievable using ViewBag.ReturnUrl ? How can I do that?

Using VS2015, .Net 4.6.2. I have a razor view that generates a visual studio error:

Error   CS1980  Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference?

This error only occurs when the view file is actually open. It seems related to the web.config in the views folder, but I cant see where:

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="Sitecore.Mvc.Presentation" />
        <add namespace="Sitecore.Mvc" />
        <add namespace="Sitecore.Sites"/>
        <add namespace="Glass.Mapper.Sc.Web.Mvc"/>
        <add namespace="DD.Web.Constants"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.webServer>
    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>

  <system.web>
    <compilation>
      <assemblies>
        <add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
</system.web>

Here's the view:

@using Sitecore.Mvc.Analytics.Extensions
@using Sitecore.Sites


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">

<title>@Html.Sitecore().Rendering(Renderings.Core.MetaData.WindowTitleId, new { Cacheable = true, Cache_VaryByData = true })</title>
<meta name="description" content="@Html.Sitecore().Rendering(Renderings.Core.MetaData.METADescriptionId, new { Cacheable = true, Cache_VaryByData = true })" />
<meta name="keywords" content="@Html.Sitecore().Rendering(Renderings.Core.MetaData.METAKeywordsId, new { Cacheable = true, Cache_VaryByData = true })" />
<link rel="canonical" href="@Html.Sitecore().Rendering(Renderings.Core.MetaData.CanonicalUrlId, new { Cacheable = true, Cache_VaryByData = true })" />
@{
    var robotsTag = Html.Sitecore().Rendering(Renderings.Core.MetaData.RobotsTag, new { Cacheable = true, Cache_VaryByData = true });
    if (robotsTag != null && !String.IsNullOrEmpty(robotsTag.ToString()))
    {
        @Html.Raw("<meta name=\"robots\" content=\"" + robotsTag + "\" />");
    }
}

<link rel="shortcut icon" href="/favicon-@(SiteContext.Current.Name.ToLower()).ico">
<link rel="icon" href="/favicon-@(SiteContext.Current.Name.ToLower()).ico">
<meta name="viewport" content="user-scalable=no">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i" rel="stylesheet">
<!--[if (gt IE 8) | (IEMobile)]><!-->
<link rel="stylesheet" href="/presentation/static/gaming/@SiteContext.Current.Name.ToLower()/dist/css/main.css">
<!--<![endif]-->
<!--[if lt IE 9]>
    <link rel="stylesheet" href="/presentation/static/gaming/@SiteContext.Current.Name.ToLower()/dist/css/oldie.css">
    <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

@{
    var extraPageCssClass = Sitecore.Context.PageMode.IsExperienceEditor ? "page-editor-mode" : "";
        ViewBag.ExtraPageCssClass = extraPageCssClass;
    }

    @Html.Sitecore().VisitorIdentification()

    @Html.Sitecore().Rendering(Renderings.Core.Global.HeadHTML, new { Cacheable = true, Cache_VaryByData = true })
</head>
<body class="@Html.Action("BodyCssClass", "Global") @ViewBag.ExtraPageCssClass">

@Html.Sitecore().Rendering(Renderings.Core.Global.BodyHTML, new { Cacheable = true, Cache_VaryByData = true })
<div class="container">
    @Html.Sitecore().Placeholder("header")
    <main role="main" id="main">
        @Html.Sitecore().Placeholder("pagebanner")

        @Html.Sitecore().Placeholder("maincontent")
    </main>
    @Html.Sitecore().Placeholder("footer")
</div>
@if (!(Sitecore.Context.PageMode.IsExperienceEditor && Sitecore.Context.User.IsAuthenticated))
{
    @*<script data-main="/presentation/static/gaming/@(SiteContext.Current.Name.ToLower())/dist/js/@(SiteContext.Current.Name.ToLower()).main" src="/presentation/static/gaming/@(SiteContext.Current.Name.ToLower())/dist/js/lib/require.js"></script>*@
    <script data-main="/presentation/static/gaming/@(SiteContext.Current.Name.ToLower())/dist/js/@(SiteContext.Current.Name.ToLower()).main" src="/presentation/static/gaming/@(SiteContext.Current.Name.ToLower())/dist/js/lib/require.js"></script>
}
</body>
</html>

http://abcds.azurewebsites.net/scripts/abdsk.json

This file is available in the azure. But when i go to "http://abcds.azurewebsites.net/scripts/abdsk.json" i get a response back saying

GET http://abcds.azurewebsites.net/scripts/abdsk.json 404 (Not Found)

What might be the cause?

i want to make webservice to login and fetch data from the website the problem is: to login there is two forms, first one you need to provide your id and press button called next then in the second one you enter you password and press login how can i scrap this ?

I am trying to show the icon/image of a model from database. In my database I have place that holds the image location as filename.png . What I have the image in my content folder of the application. But the image is not seen.

<tr>
                <td>Icon Location: </td>
                <td>ahmeteasi.png</td>
                <td> <img src="/Contents/ahmeteasi.png" />  </td>
            </tr>

In my view, I have sometihng like this.

        <td> <img src="@Url.Content(String.Format("~/Contents/{0}", Model.appIconLocation))" />  </td>

Even though the page source shows it right. I cannot see it. where is the problem.Thank you This is the error. when I click it from page source

This question already has an answer here:

Im brand new to C# and am trying to figure out how to add another variable to this if statement. It currently checks the database to see if a user has an an account level of 2 and if so it restricts certain actions. I would like it to check for account level 3 as well and preform the same action. So basically: if (uType==2 && 3), but im not sure this is the correct format.

Any help would be appreciated, thanks!

int uType = getUlevel(Accountid.Text);
if (uType==2) // I want it to check if uType is 2 or 3 here.
{
    transferOK.Text = "2";
    return;
}

I have an entity which contains two similar properties, AttributeValue (byte[]) and DecryptedAttributeValue (string). DecryptedAttributeValue just stores a string which will then be encrypted and saved in AttributeValue. I do not want DecryptedAttributeValue to be saved in my database.

I am trying to use code-first to call a SPROC on save opeartions, take in the all the values along with the DecryptedAttributeValue, encrypt it and save it in the AttributeValue column. However I am having a lot of issues trying to do this. One error is as follows:

A parameter binding to the property 'DecryptedAttributeValue' was not found on the modification function 'SubjectAttributeValue_Insert'. Ensure that the parameter is valid for this modification operation and that it is not database generated.

My entity

public class SubjectAttributeValue
{
   ..... // properties removed for simplification

    public int SubjectAttributeValueId { get; set; }
    public byte[] AttributeValue { get; set; }
    [NotMapped]
    public string DecryptedAttributeValue { get; set; }    
}

My DbContext

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<SubjectAttributeValue>()
            .MapToStoredProcedures(
                s => { s.Insert(i => i.Parameter(p => p.DecryptedAttributeValue, "DecryptedAttributeValue")); }
            );
    }

My SPROC (again other entities removed for simplification, this is not a 1 column table)

CREATE PROCEDURE [dbo].[SubjectAttributeValue_Insert]
    @DecryptedAttributeValue [nvarchar](255)
AS
BEGIN
    OPEN SYMMETRIC KEY xx_SymmetricKey
    DECRYPTION BY CERTIFICATE xx_Cert

    INSERT [dbo].[SubjectAttributeValues]([AttributeValue])
    VALUES (EncryptByKey(Key_GUID('GBAR_Cert'),@DecryptedAttributeValue))

    CLOSE SYMMETRIC KEY xx_Cert 

    ... // removed for simplification

END

I am using HtmlAgilityPack to perform Scraping in C #, so far I have not had problems when doing Scratch from several web, however, trying to eject the following code I get an error

Var getHtmlWeb = new HtmlWeb ();
Var home page = getHtmlWeb.Load ("https://www.corfo.cl/");

The error that appears is:

"Connection terminated: Unexpected sending error."

The only web that is giving me problems is Corfo and not how to solve this. I appreciate your help

I have a website solution created in VS 2015 and have added a project to manage the Data Access C# functions. The data access project is defined to the namespace "MyCo.DataAccess" and generates a DLL file (coDataAccess.dll) which is then referenced in the website project. The C# code behind the asp page contains a reference to the namespace.

using MyCo.DataAccess;

In development, builds are good & everything works as expected with references to the dependent functions. When testing the website, however, an error occurs:

Compiler Error Message: CS0234: The type or namespace name 'DataAccess' does not exist in the namespace 'MyCo' (are you missing an assembly reference?)

Source Error:        
Line 6:  using System.Web.UI;
Line 7:  using System.Web.UI.WebControls;
Line 8:  using MyCo.DataAccess;

There has been multiple possible solutions, but none have worked yet:

  • Signing the DLL and adding it as an assembly reference in the web.config
  • Clearing out the obj folder and rebuilding

Thanks in advance.

@Html.DropDownListFor(m => m.CategoryId, new SelectList(Model.CategoryLookUp, "Value", "Text"), new { @class = "form-control" })

==> Here I can Select element by Id, $("#CategoryId").val() //etc. but I want to select All "Html.DropDownListFor" or any kind of helper to add a css class.

I just simply add new " { @class = "form-control myClass" }) ", and it works fine, but over 1000+ dropdownList have in my project, for that I wrote a class, and now i want to add this class to all dropdownList.

I have a .NET Core web app which has an API. I've defined an Middleware class based on this answer like so:

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate next;
    private readonly ILogger logger;

    public ErrorHandlingMiddleware(RequestDelegate next,
        ILoggerFactory loggerFactory)
    {
        this.next = next;
        logger = loggerFactory.CreateLogger<ErrorHandlingMiddleware>();
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            logger.LogError(0, ex, "An unhandled exception has occurred: " + ex.StackTrace);
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        var code = HttpStatusCode.InternalServerError;
        var message = exception.Message;
        if (exception is BadRequestException)
        {
            code = HttpStatusCode.BadRequest;
        }
        else if (exception is NotFoundException)
        {
            code = HttpStatusCode.NotFound;
        }
        else if (exception is NotAuthorizedException)
        {
            code = HttpStatusCode.Forbidden;
        }
        else if (exception is NotAuthenticatedException)
        {
            code = HttpStatusCode.Unauthorized;
        }
        else
        {
            message = "An unexpected error occurred.";
        }

        var result = JsonConvert.SerializeObject(new { error = message });
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;
        return context.Response.WriteAsync(result);
    }
}

The error handling only handles when an exception is thrown in code. A bad route does not throw an exception. The problem is that if I try to access a non-existent API route - that is, one that follows the API route convention and starts with "/api/adfasdf" - the API returns HTML (or the error page or the home page, I forget).

I've received some suggestions to check the context.Response.StatusCode after await next(context); executes, but it's 200.

How can I configure my web app such that it recognizes a bad API route and returns a 404?

UPDATE Here is where/when I load the middleware in my Startup class:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime, IOptions<OidcConfig> oidcConfigOptions)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    // Add Serilog to the logging pipeline
    loggerFactory.AddSerilog();

    app.UseMiddleware<ErrorHandlingMiddleware>();

    if (env.IsLocal())
    {
        app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
        {
            HotModuleReplacement = true
        });
    }

    var oidcConfig = oidcConfigOptions.Value;

    // Configure the app to use Jwt Bearer Authentication
    app.UseJwtBearerAuthentication(new JwtBearerOptions
    {
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        Authority = oidcConfig.GetAuthority(),
        Audience = oidcConfig.ResourceAppId,
        TokenValidationParameters = new TokenValidationParameters
        {
            RequireExpirationTime = true,
            RequireSignedTokens = true,
            ValidateAudience = true,
            ValidIssuer = oidcConfig.GetIssuer(),
            ValidateIssuer = true,
            ValidateActor = false,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true
        },
    });

    app.UseSiteIdClaimInjection();

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");

        routes.MapSpaFallbackRoute(
            name: "spa-fallback",
            defaults: new { controller = "Home", action = "Index" });
    });

    appLifetime.ApplicationStopped.Register(() => this.ApplicationContainer.Dispose());
}

Here's the situation.

I have a save, and a print button :

<input name="btnSubmit" type="submit" value="Save" /> 
<input name="btnSubmit" type="submit" value="Print"/> @*Redirect to Action("Print", "controler")*@

But the print button has to open a new tab. If it was just me, I obviously know I have to save before printing... it would not be an issue. I could use this link with target blank instead :

<a target="_blank" href="@Url.Action("Print", "controler", new { id = Model.id })" type="submit" value="Print" > Print</a>

Easy, but now some users think that the print button should ALSO save the page. Because they don't push save... they just print and the model changes are lost because I can't call the post action in my print link... it's a link.

I thought, at first, that I could make an asynchronous call to a save fonction, but my model is way too big, it requires the post back of it's own action (right ?)

Went through this :

How do I use Target=_blank on a response.redirect?

And i'm not sure if it really help in MVC... right now i'm stuck here :

[HttpPost]
public ActionResult MyForm(string btnSubmit, formModel model)
{
    if (btnSubmit == "Print")
    {
        dbSave(model);
        return RedirectToAction("Print", "controler"); // Won't open new tab... 
    }
}

I have a mediocre skill level with VS and C#. I'm attempting to add a .ascx file with codebehind to an existing project in its user controls.

Right-clicking UserControls -> Add -> New Item and searching "web user control" returns "No items found."

Copy-pasting an existing .ascx file (there are more than a dozen) successfully creates the new .ascx file, but there's no .ascx.cs or .ascx.designer.cs files attached and no apparent way to add them.

More information

Copying "MyUserControl.ascx" was indeed copying the codebehind files, but they were copied under the original "MyUserControl.ascx" file as "MyUserControl - Copy.ascx.cs" and ""MyUserControl - Copy.ascx.designer.cs". VS does not allow these files to be renamed or moved.

So, I removed these files from the project, changed their names in file explorer, added them back to the project and updated the code as I needed.

However, they don't appear nested, but on the same level as the .ascx files.

Also tried

Created a blank web app and could add it there, so it's something project-specific.

Tried adding the file as existing after copying in file explorer, with the intent to generate the code behind files - there's no Convert to Web Application option, even when selecting the solution directly and even under the project menu in VS2015 for my project, as suggested by How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

I'm running Visual Studio 2015 Enterprise Update 1.

I created an empty Visual Basic ASP.NET Website targeting the .NET Framework 4.5.2. And I want to convert it to an ASP.NET Web Application.

Under the Website's context menu in Solution Explorer there is no "Convert to Web Application" menu-item, nor is there anything under the Website menu in the main-menu bar:

enter image description here

enter image description here

Where has the feature gone? Has it been removed completely in Update 1?

I am developing a little project for a local school and I am pretty much what you can call a newbie in programming. I am trying to retrieve a selected date by the user in the calendar to save to a separate database. I have an Entity Framework model (.edmx) to link the table in Visual Studio that I need. This is what I got so far:

ASP.net:

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="main_banner">
    </div>
    <div class="main_container">
        <div class="main_heading">
            <h1 class="main_title">Projector Inspection</h1>
            <p><a href="AddProjector.aspx">Add</a> new Projector</p>
        </div>
        <div class="info_container">
            <div>
                <asp:Label ID="RoomNolbl" runat="server" Text="Room No:"></asp:Label>
             </div>
            <div>
                <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="Roomsdbo" DataTextField="Room_No" DataValueField="Room_No" AutoPostBack="True">
                    <asp:ListItem>---Select Room---</asp:ListItem>
                </asp:DropDownList> 
                <asp:SqlDataSource ID="Roomsdbo" runat="server" ConnectionString="<%$ ConnectionStrings:iPadLoanConnectionString2 %>" SelectCommand="SELECT [Room_No] FROM [tblRooms]"></asp:SqlDataSource>
             </div>

             <div>
                <asp:Label ID="Datelbl" runat="server" Text="Date Checked:"></asp:Label>
             </div>
            <div>
                <asp:Calendar ID="Calendar1" runat="server" BackColor="White" BorderColor="White" BorderWidth="1px" Font-Names="Verdana" Font-Size="9pt" ForeColor="Black" Height="190px" NextPrevFormat="FullMonth" Width="350px" OnSelectionChanged="Calendar1_SelectionChanged1" DayNameFormat="Shortest">
                    <DayHeaderStyle Font-Bold="True" Font-Size="8pt" />
                    <NextPrevStyle Font-Bold="True" Font-Size="8pt" ForeColor="#333333" VerticalAlign="Bottom" />
                    <OtherMonthDayStyle ForeColor="#999999" />
                    <SelectedDayStyle BackColor="#333399" ForeColor="White" />
                    <TitleStyle BackColor="White" BorderColor="#ae1022" BorderWidth="4px" Font-Bold="True" Font-Size="12pt" ForeColor="#ae1022" />
                    <TodayDayStyle BackColor="#CCCCCC" />
                </asp:Calendar>
                <asp:TextBox ID="Calendartxt" runat="server" ReadOnly="True"></asp:TextBox>
             </div>

            <div class ="info_container_task">
                <h3>Task carried</h3>
            <div>
                <asp:Label ID="CheckBoxFilterlbl" runat="server" Text="Filter Cleaning:"></asp:Label>
                <asp:CheckBox ID="CheckBoxFilter" runat="server" OnCheckedChanged="CheckBoxFilter_CheckedChanged" AutoPostBack="true" />
            </div>
            <div>
                <asp:Label ID="CheckBoxBulblbl" runat="server" Text="Bulb Replacement:"></asp:Label>
                <asp:CheckBox ID="CheckBoxBulb" runat="server"  OnCheckedChanged="CheckBoxBulb_CheckedChanged" AutoPostBack="true"/>
            </div>
            <div>
                <asp:Button ID="ButtonSubmit" runat="server" Text="Submit" OnClick="ButtonSubmit_Click" />
            </div>
          </div>
             <div>
                <asp:Label ID="HourCountBulblbl" runat="server" Text="Bulb Hours:"></asp:Label>
             </div>
            <div>
                <asp:TextBox ID="HourBulbtxt" runat="server" ></asp:TextBox>
             </div>
            <div>
                <asp:Label ID="FilterHourlbl" runat="server" Text="Filter Hours:"></asp:Label>
            </div>
            <div>
                <asp:TextBox ID="FilterHourtxt" runat="server" ></asp:TextBox>
            </div>
             <div>
                <asp:Label ID="Commentslbl" runat="server" Text="Additional Comments:" ></asp:Label>
             </div>
            <div>
                <textarea id="Commentstxt" cols="20" rows="2" ></textarea>&nbsp;</div>
        </div>

    </div>
<div class="sub_container">
    <h2>Additional Information</h2>
<div class="Tbl_Projectorinfo">
    <div class="projectorGrid">
            <asp:GridView ID="projectorinfo" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="linkprojectorsdbo" ForeColor="#333333" GridLines="None" DataKeyNames="Model_No">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <Columns>
                    <asp:BoundField DataField="Current_Hours" HeaderText="Current_Hours" SortExpression="Current_Hours" />
                    <asp:BoundField DataField="Last_Replacement_Date" HeaderText="Last_Replacement_Date" SortExpression="Last_Replacement_Date" />
                    <asp:BoundField DataField="Last_Cleaned" HeaderText="Last_Cleaned" SortExpression="Last_Cleaned" />
                </Columns>
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#ae1022" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#ae1022" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>
        </div>
            <asp:SqlDataSource ID="linkprojectorsdbo" runat="server" ConnectionString="<%$ ConnectionStrings:iPadLoanConnectionString %>" SelectCommand="SELECT [Model_No], [Current_Hours], [Last_Replacement_Date], [Last_Cleaned] FROM [tblProjectors] WHERE ([Room_No] = @Room_No)">
                <SelectParameters>
                    <asp:ControlParameter ControlID="DropDownList1" Name="Room_No" PropertyName="SelectedValue" Type="String" />
                </SelectParameters>
            </asp:SqlDataSource>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="tblModels" CellPadding="4" ForeColor="#333333" GridLines="None">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <Columns>
                    <asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" SortExpression="Manufacturer" />
                    <asp:BoundField DataField="Model_Name" HeaderText="Model" SortExpression="Model_Name" />
                    <asp:BoundField DataField="Min_Hours" HeaderText="MinHours" SortExpression="Min_Hours" />
                    <asp:BoundField DataField="Max_Hours" HeaderText="MaxHours" SortExpression="Max_Hours" />
                </Columns>
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#ae1022" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#ae1022" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>
            <asp:SqlDataSource ID="tblModels" runat="server" ConnectionString="<%$ ConnectionStrings:iPadLoanConnectionString %>" SelectCommand="SELECT [Manufacturer], [Model_Name], [Min_Hours], [Max_Hours] FROM [ProjectorsRoom2017] WHERE ([Room_No] = @Room_No)">
                <SelectParameters>
                    <asp:ControlParameter ControlID="DropDownList1" Name="Room_No" PropertyName="SelectedValue" Type="String" />
                </SelectParameters>
            </asp:SqlDataSource>
        </div>
    </div>

.cs File:

 protected void ButtonSubmit_Click(object sender, EventArgs e)
    {
        tblProjector entry = new tblProjector();
        entry.Last_Cleaned = Convert.ToDateTime(Calendartxt.Text);
        iPadLoanEntities db = new iPadLoanEntities();
        db.tblProjectors.Add(entry);
        db.SaveChanges();
    }




    protected void Calendar1_SelectionChanged1(object sender, EventArgs e)
    {
        Calendartxt.Text = Calendar1.SelectedDate.ToShortDateString();
    }
}

I am constantly getting an error saying validation for one or more than one entities failed. Also the error points to the line of code:

db.SaveChanges();

I know that with that code I am trying to get the information of the TextBox that is linked to the calendar to be saved to the database but to be honest saving it directly from the calendar would be great if it is possible.

If anyone could give me a hand on how to be able to achieve this I would be grateful. Thanks

This question already has an answer here:

With .NET-Core apps the configuration data read from some file/environment is loaded into an IConfigurationRoot instance. But I keep seeing examples that show that the injected instance is an IOptions<T> .. not an IConfigurationRoot.

  • Why IOptions?
  • What is the advantage of this class instead of just having my own AppSettings POCO?
  • Do I need to do it this way? Is there another way?

For example..

public static IConfigurationRoot Configuration { get; set; }

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
                                            .AddJsonFile("appSettings.json", true, true)
                                            .AddJsonFile($"appSettings.{env.EnvironmentName}.json", true)
                                            .AddEnvironmentVariables();
    Configuration = builder.Build();
}

public void ConfigureServices(IServiceCollection services)
{
    // Register the IConfiguration instance which MyOptions binds against.
    services.Configure<AppConfiguration>(Configuration);

    // <snip other stuff>
}

public AccountController(IOptions<AppConfiguration> appConfiguration)
{
    // do stuff with appConfiguration here.
}

I'm trying to implement a nested gridview with expand/collapse functionality. My problem is that the jquery click function is not working. The scenario is as follows:

JQUERY:

$("[src*=plus]").on("click", "img", function () {
            alert('hi');
            $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
            $(this).attr("src", "images/minus.png");
        });
        $("[src*=minus]").on("click", "img", function () {
            $(this).attr("src", "images/plus.png");
            $(this).closest("tr").next().remove();
        });

GRIDVIEW:

<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"
        DataKeyNames="Id" OnRowDataBound="OnRowDataBound">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <img alt = "" style="cursor: pointer" src="images/plus.png" />
                    <asp:Panel ID="pnlOrders" runat="server" Style="display: none">
                        <asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false">
                            <Columns>
                                <asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Order Id" />
                                <asp:BoundField ItemStyle-Width="150px" DataField="Policy" HeaderText="Date" />
                            </Columns>
                        </asp:GridView>
                    </asp:Panel>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField ItemStyle-Width="150px" DataField="Id" HeaderText="Contact Name" />
            <asp:BoundField ItemStyle-Width="150px" DataField="Name" HeaderText="City" />
        </Columns>
    </asp:GridView>

Now, if I change the .on() method with the .live() method, then it works just fine. Any of you jQuey savvy people know what I'm doing wrong. Thanks!