Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Why is this so complicated in ASP.NET?

Options
2

Comments

  • Closed Accounts Posts: 7,097 ✭✭✭Darragh29


    Draupnir wrote: »
    The good news for you is that you can develop a strong Data Access Layer in C Sharp which you can reuse across all your projects, so once you learn to do this once, you can plug that layer into all your websites.

    If you do it well of course and approach it from a multi tiered architecture point of view.

    Of course, you could make all those projects work with single layer applications and they would be fine. However, you would be doing Number of Projects * Data Access Layer amount more work than you need to and you would be exposing yourself to poor design and security risks galore.

    It's not even that steep a learning curve, 2/3 days of doing online ADO.net and C Sharp tutorials will teach you all you need to know to write a nice reusable data access layer assembly.

    I have to say, I'm not all that comfortable with all these drag and drop solutions, I want to learn the proper way of doing it because what this essentially is, is a major career change in my early 30's, so this is what I'll be at for the forseeable future and I'll have to learn how to do it right... Some of the projects I've been asked to do are not exactly small, I've one guy who owns a major motor factor and wants to start selling parts through his website, so it's not just some small personal site I want to develop, this is the real deal and I have to learn it right. I've did degree in electronic engineering years ago and had some exposure to C and C++ in 1st & 2nd year, although I tried to avoid it where I could because the I didn't like the lecturer and I wanted the programs to be able to run in windows but all the things we did were dos prompt applictaions! Now I wish I had been a bit less narrow minded back then!


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    If you want to use a data access layer you could play around with the Enterprise Library - that comes with a DAL ready baked for you. Although from a learning perspective you would benefit from writing your own.


  • Registered Users Posts: 3,548 ✭✭✭Draupnir


    Evil Phil wrote: »
    If you want to use a data access layer you could play around with the Enterprise Library - that comes with a DAL ready baked for you. Although from a learning perspective you would benefit from writing your own.

    Plus he will waste about 3 days trying to navigate that damn MSDN web library! :)


  • Closed Accounts Posts: 7,097 ✭✭✭Darragh29


    eoin_s wrote: »
    What part exactly is complicated? ASP.Net is not a scripting language (and it's not ASP either, so best not to confuse the two), so of course there's going to be a learning curve. I don't even find it that cumbersome for small applications either.

    I've not used Visual Web developer, but if it's similar to Visual Studio then try something like this.

    Bear in mind that this is not tested and is just off the top of my head. If it does happen to work, then it's far from best practise, but may be enough to get you started.

    The ASPX page:
    [html]
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="page.aspx.cs" Inherits="page" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

    <html xmlns="http://www.w3.org/1999/xhtml&quot; >
    <head runat="server">
    <title>Untitled Page</title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    Dropdown list 1: <asp:DropDownList ID="DropDownList1" runat="server"><asp:ListItem Value="1" Text="1" /></asp:DropDownList><br />
    Dropdown list 2: <asp:DropDownList ID="DropDownList2" runat="server"><asp:ListItem Value="1" Text="1" /></asp:DropDownList><br />
    Dropdown list 3: <asp:DropDownList ID="DropDownList3" runat="server"><asp:ListItem Value="1" Text="1" /></asp:DropDownList><br />
    Dropdown list 4: <asp:DropDownList ID="DropDownList4" runat="server"><asp:ListItem Value="1" Text="1" /></asp:DropDownList><br />
    Dropdown list 5: <asp:DropDownList ID="DropDownList5" runat="server"><asp:ListItem Value="1" Text="1" /></asp:DropDownList><br />
    <p />
    TextBox 1: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
    TextBox 2: <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <p/>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    </form>
    </body>
    </html>
    [/html]

    The code behind page (C#):
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    
    public partial class page : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            string dropdown1 = DropDownList1.SelectedValue;
            string dropdown2 = DropDownList2.SelectedValue;
            string dropdown3 = DropDownList3.SelectedValue;
            string dropdown4 = DropDownList4.SelectedValue;
            string dropdown5 = DropDownList5.SelectedValue;
    
            string textbox1 = TextBox1.Text;
            string textbox2 = TextBox2.Text;
    
            string sql = "insert into tablename(column1, column2, column3, column4, column5, column6, column7)\n";
            sql += "values(";
            sql += "'" + dropdown1 + "',";
            sql += "'" + dropdown2 + "',";
            sql += "'" + dropdown3 + "',";
            sql += "'" + dropdown4 + "',";
            sql += "'" + dropdown5 + "',";
            sql += "'" + textbox1 + "',";
            sql += "'" + textbox2 + "'";
            sql += ")";        
    
            SqlConnection conn = new SqlConnection("Your Connection String");
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);        
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();        
            conn.Close();
        }
    }
    

    A small question... If I want to replace one of my drop down lists with two grouped radio buttons, how do I handle this when I get to this part of the code:

    string dropdown5 = DropDownList5.SelectedValue;

    The problem I have is that I've two radio buttons, say petrol_button and disesel_button and I have grouped these using MS Visual Developer Express so that only one button can be clicked at a time. I have a database column called "Fuel" and I only want either Petrol or Diesel to be inserted.

    I've tried messing around with:

    string radiobutton1 = RadioButton1.SelectedValue;
    string radiobutton2 = RadioButton2.SelectedValue;

    I know this is hard to believe, but I did have this set up in PHP and it wasn't a problem! This is going over my head again! It's not clicking with me how to tie the two radio buttons into the string bit with my group name...


  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    I can't remember off the top of my head, and don't have visual studio on the home PC, but I think you need to check if the radio button is checked or not

    string fuelType="";
    if (radPetrol.Checked)
    {
    fuelType = "petrol";
    }
    else if (radDiesel.Checked)
    {
    fuelType = "diesel";
    }


  • Advertisement
  • Moderators, Science, Health & Environment Moderators Posts: 8,956 Mod ✭✭✭✭mewso


    The radiobuttonlist is handy for this kind of thing too. Use one for each group and simple access it's selecteditem.value.


  • Closed Accounts Posts: 7,097 ✭✭✭Darragh29


    musician wrote: »
    The radiobuttonlist is handy for this kind of thing too. Use one for each group and simple access it's selecteditem.value.

    Ok, the group name for my two radio buttons is Trans_Type, containing two radio buttons, one called Installation and one called Maintenance

    Does this look right???

    string = My_Trans_Type = RadioButtonList.Trans_Type.SelectedValue;

    ???

    I had expected to be able use the format below:

    string dropdown5 = DropDownList5.SelectedValue;

    But change the above for my radio button group so I'd end up with...

    string My_Trans_Type = Trans_Type.SelectedValue;

    and then insert My_Trans_Type into my daatabase using the INSERT function...

    But this won't work...


  • Moderators, Science, Health & Environment Moderators Posts: 8,956 Mod ✭✭✭✭mewso


    o.k a few things about the radiobuttonlist first. The radiobuttonlist by default uses a table for layout which is a big no-no as far as I am concerned. So this is where RepeatLayout comes in to play. Setting it to flow means no table. You can also set the repeat direction. So if you have a radiobuttonlist like the following:-
    <asp:RadioButtonList ID="Trans_Type" runat="server" RepeatLayout="Flow" RepeatDirection="Horizontal">
       <asp:ListItem Value="1" Text="Type 1" Selected="True"></asp:ListItem>
       <asp:ListItem Value="2" Text="Type 2"></asp:ListItem>
    </asp:RadioButtonList>
    

    then Trans_Type.selecteditem.value will give me "1" or "2" depending on which one was selected. I've always had issues with selectedvalue even in the dropdownlist so I've gotten into the habit using selecteditem which seems to consistently return the correct value or text.


  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    [html]
    <asp:RadioButtonList ID="RadioButtonList1" runat="server">
    <asp:ListItem Value="Installation">Installation</asp:ListItem>
    <asp:ListItem Value="Maintenance">Maintenance</asp:ListItem>
    </asp:RadioButtonList>
    [/html]
      if (IsPostBack)
            {
                string radioValue = RadioButtonList1.SelectedItem.Value;
                Response.Write(radioValue);
            }
    

    Edit - that will cause an error if a value isn't selected, so be sure to handle that.


  • Closed Accounts Posts: 7,097 ✭✭✭Darragh29


    musician wrote: »
    o.k a few things about the radiobuttonlist first. The radiobuttonlist by default uses a table for layout which is a big no-no as far as I am concerned. So this is where RepeatLayout comes in to play. Setting it to flow means no table. You can also set the repeat direction. So if you have a radiobuttonlist like the following:-
    <asp:RadioButtonList ID="Trans_Type" runat="server" RepeatLayout="Flow" RepeatDirection="Horizontal">
       <asp:ListItem Value="1" Text="Type 1" Selected="True"></asp:ListItem>
       <asp:ListItem Value="2" Text="Type 2"></asp:ListItem>
    </asp:RadioButtonList>
    

    then Trans_Type.selecteditem.value will give me "1" or "2" depending on which one was selected. I've always had issues with selectedvalue even in the dropdownlist so I've gotten into the habit using selecteditem which seems to consistently return the correct value or text.

    But the code you have above is for a HTML page. I need mine to go into a c# page...??? I'm lost, that might not have even made sense what I just said! :confused::confused::confused:


  • Advertisement
  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    That code is for the ASPX page. Those are not HTML tags, they are ASP.Net controls that will be transformed into HTML.

    Your C# page will then reference those controls.

    PS - I didn't see Musician's post when I posted my reply - his one sample is better.

    Edit - here are some tutorials
    http://www.w3schools.com/ASPNET/default.asp


  • Closed Accounts Posts: 7,097 ✭✭✭Darragh29


    eoin_s wrote: »
    That code is for the ASPX page. Those are not HTML tags, they are ASP.Net controls that will be transformed into HTML.

    Your C# page will then reference those controls.

    PS - I didn't see Musician's post when I posted my reply - his one sample is better.

    Edit - here are some tutorials
    http://www.w3schools.com/ASPNET/default.asp

    But that's my problem, how to reference them in my c# script.


  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    Darragh29 wrote: »
    But that's my problem, how to reference them in my c# script.

    That's in the code I posted earlier.
    string radioValue = RadioButtonList1.SelectedItem.Value;
    


  • Registered Users Posts: 9,557 ✭✭✭DublinWriter


    Darragh29 wrote: »
    One tutorial shows you how to design an excellent webform that uses drop down lists, text boxes and all sort of controls for allowing a user to enter data, but did nobody stop to think about showing you how to handle the data into a database once the submit button is hit???
    I'm not sure where you're at or going with this?!? Inserting data into a database has to be one of the simplest tasks ever. It should take you about 5 minutes and zero lines of hand-written code!

    Drop in your SQLDatasource component, set up your Connection String, select your table, allow it to automatically generate insert and update statements, drop in your formview, connect it to your SQLDatasource and voila!

    Didn't you use the InsertItem template in the Formview?


  • Moderators, Science, Health & Environment Moderators Posts: 8,956 Mod ✭✭✭✭mewso


    There are two parts to an asp.net page. The html part and the code part.

    The html part is a .aspx file and you can put asp.net controls like the radiobuttonlist in with the html. When you open a .aspx in the browser .net converts any asp.net controls to valid html.

    The second part is the code behind the page which is either a .aspx.vb (vb.net) or .aspx.cs (c#). This code allows you to intercept and make changes to the rendering of the page. When a user submits a page you can query the status of controls on the page. In this case in your code you can query the selecteditem.value property of the radiobuttonlist.

    I just posted an example of the radiobuttonlist because I think it's important to know how it works. The quick answer to your problem was simply to use selecteditem.value instead of selectedvalue.

    It is well worth looking at the page life cycle of an asp.net page to see whats going on behind the scenes. It's a total change from the way you might have worked with php.


  • Closed Accounts Posts: 7,097 ✭✭✭Darragh29


    musician wrote: »
    There are two parts to an asp.net page. The html part and the code part.

    The html part is a .aspx file and you can put asp.net controls like the radiobuttonlist in with the html. When you open a .aspx in the browser .net converts any asp.net controls to valid html.

    The second part is the code behind the page which is either a .aspx.vb (vb.net) or .aspx.cs (c#). This code allows you to intercept and make changes to the rendering of the page. When a user submits a page you can query the status of controls on the page. In this case in your code you can query the selecteditem.value property of the radiobuttonlist.

    I just posted an example of the radiobuttonlist because I think it's important to know how it works. The quick answer to your problem was simply to use selecteditem.value instead of selectedvalue.

    It is well worth looking at the page life cycle of an asp.net page to see whats going on behind the scenes. It's a total change from the way you might have worked with php.

    Yeah, it's a big change all right, I don't think I'm ready for it! This seems daunting, everything seemed simpler with PHP...


  • Moderators, Science, Health & Environment Moderators Posts: 8,956 Mod ✭✭✭✭mewso


    Darragh29 wrote: »
    Yeah, it's a big change all right, I don't think I'm ready for it! This seems daunting, everything seemed simpler with PHP...

    Trust me once you get your head around it you'll never look back. It's always fun to knock Microsoft but asp.net is one of the best things they have ever done imo.


  • Closed Accounts Posts: 7,097 ✭✭✭Darragh29


    musician wrote: »
    Trust me once you get your head around it you'll never look back. It's always fun to knock Microsoft but asp.net is one of the best things they have ever done imo.

    Thats why I made the jump because I wanted to do it proper and professionally rather than just knock it together which was how I went at it until now! Patience patience! :o


  • Registered Users Posts: 3,548 ✭✭✭Draupnir


    I'm not sure where you're at or going with this?!? Inserting data into a database has to be one of the simplest tasks ever. It should take you about 5 minutes and zero lines of hand-written code!

    Drop in your SQLDatasource component, set up your Connection String, select your table, allow it to automatically generate insert and update statements, drop in your formview, connect it to your SQLDatasource and voila!

    Didn't you use the InsertItem template in the Formview?

    I highly advise that nobody ever uses SQLDataSources or any drag and drop functionality in their .NET development. It creates crap code that performs terribly, it also means that a chimp could be trained to do your job and that is not a good thing!


  • Moderators, Science, Health & Environment Moderators Posts: 8,956 Mod ✭✭✭✭mewso


    Draupnir wrote: »
    I highly advise that nobody ever uses SQLDataSources or any drag and drop functionality in their .NET development. It creates crap code that performs terribly, it also means that a chimp could be trained to do your job and that is not a good thing!

    But then a chimp could probably be trained to drag and drop a linqdatasource too and I'd have no problem with that. I agree though. There is no need to use the sqldatasource. It was handy back in the day when it was the only option for that idiot boss who wanted someting done yesterday but he can have it yesterday with Linq now.


  • Advertisement
  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    Darragh29 wrote: »
    Yeah, it's a big change all right, I don't think I'm ready for it! This seems daunting, everything seemed simpler with PHP...

    Darragh, think about it this way - if you are familiar with HTML and JavaScript, then you know to add an event to an element.

    For instance, if you wanted to add some JavaScript that checks that a form value has been submitted, then you would add an "onclick" event to the button that calls a function you have defined in a .js file.

    In your ASP.NET page, it's not that different - you have a click event for your button that calls a function that can reference the elements on your page.

    I don't want to cause any confusion between client and server-side coding, but I think .net is probably considered more event driven then scripting technologies like ASP and PHP, where it's just lots of linear code that is largely run in sequence.

    The others on this thread clearly have a lot more .net experience than I do, so they may totally disagree with me on the above, but it's how I was able to get my head around the difference between ASP coding and ASP.net.


  • Registered Users Posts: 3,548 ✭✭✭Draupnir


    musician wrote: »
    But then a chimp could probably be trained to drag and drop a linqdatasource too and I'd have no problem with that. I agree though. There is no need to use the sqldatasource. It was handy back in the day when it was the only option for that idiot boss who wanted someting done yesterday but he can have it yesterday with Linq now.

    I personally prefer the approach of having a generic data access layer that can call any named stored procedure. Then I just need to write new stored procs for any task a project needs.

    In that way, its hopefully a one off deployment off the web app and any updating of the site is done in the procs, meaning I have zero downtime of the site if all goes to plan.


  • Moderators, Science, Health & Environment Moderators Posts: 8,956 Mod ✭✭✭✭mewso


    eoin_s wrote: »
    Darragh, think about it this way - if you are familiar with HTML and JavaScript, then you know to add an event to an element.

    For instance, if you wanted to add some JavaScript that checks that a form value has been submitted, then you would add an "onclick" event to the button that calls a function you have defined in a .js file.

    In your ASP.NET page, it's not that different - you have a click event for your button that calls a function that can reference the elements on your page.

    I don't want to cause any confusion between client and server-side coding, but I think .net is probably considered more event driven then scripting technologies like ASP and PHP, where it's just lots of linear code that is largely run in sequence.

    The others on this thread clearly have a lot more .net experience than I do, so they may totally disagree with me on the above, but it's how I was able to get my head around the difference between ASP coding and ASP.net.

    I would agree with your description in terms of a page. The way I originally got my head around it was to realize that it wasn't a million miles from php/asp except it was putting a very nice model on top of it all. At the end of the day your page has to be valid html that a browser can read. Now in asp/php we would have scripted our If and else code in the order we needed certain html to appear on the page. In asp.net we can put an asp.net literal control in it's place and then in the code behind write myliteral.text = "hello".

    It simplifies the whole process. Again instead of looping through records from a db and outputting table rows inline as I used to do I can just drop a gridview or repeater and provide a template for each row. Then in the code behind I can in layman's terms say "heres a datasource now produce the output" but I can also say "can you also run the following code before you create the html for the row" by writing the code for a rowdatabound event so I retain huge control with a cleaner model.


  • Moderators, Science, Health & Environment Moderators Posts: 8,956 Mod ✭✭✭✭mewso


    Draupnir wrote: »
    I personally prefer the approach of having a generic data access layer that can call any named stored procedure. Then I just need to write new stored procs for any task a project needs.

    Ah I'm afraid I refuse to use SPs anymore for CRUD. I'm a paramaterised query man myself. I have always writen my own business objects and data access layer but I'm giving Linq serious consideration as I do like the look of it.
    Draupnir wrote: »
    In that way, its hopefully a one off deployment off the web app and any updating of the site is done in the procs, meaning I have zero downtime of the site if all goes to plan.

    Surely if the schema changes or new stored procedures need to be added your web code will have to change too? Unfortunately I live in a world where I am asked to build an application in a week. Then when they use and start thinking of other things it should do for them they come back to me with a list of features. Basically all my web apps evolve continually. I would of course love to develop projects the right way but I've never been given the choice.


  • Closed Accounts Posts: 7,097 ✭✭✭Darragh29


    Right, I've put:

    <asp:RadioButtonList ID="RadioButtonList1" runat="server" Style="z-index: 102; left: 27px;
    position: absolute; top: 215px">
    <asp:ListItem Value="Install">Installation</asp:ListItem>
    <asp:ListItem Value="Main">Maintenance</asp:ListItem>
    </asp:RadioButtonList>

    Into my aspx page and I've put:

    string radioValue = RadioButtonList1.SelectedItem.Value;

    into my .cs page,


    and I've also added this to my code on the .cs page

    sql += "'" + radioValue + "'";

    And I'm not getting an error when debugging the project but when I try to post the data on the page using the button, I get an error at line 45 in my code

    cmd.ExecuteNonQuery();

    saying:

    "String or binary data would be truncated.\r\nThe statement has been terminated."

    And I must be learning something because I could work out that my character strings being posted were too long for the space I had assigned for them in my database!!! :D:D:D


  • Closed Accounts Posts: 7,097 ✭✭✭Darragh29


    thanks to all here for the help with this, horsing into it now!


  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    Good stuff, best of luck with the rest of the project.


  • Registered Users Posts: 2,299 ✭✭✭PixelTrawler


    Darragh29

    Didnt scan through the whole thread but did anyone point out to go to www.asp.net

    Its the microsoft learning site (more or less) source code, tutorials and starter kits etc. Pulling apart a starter kit is a good way to learn.


  • Closed Accounts Posts: 7,097 ✭✭✭Darragh29


    I'm trying to get the cascading dropdown list in this c# script to post on bottonclick to my database:



    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Web.Services;
    using System.Collections.Specialized;
    using AjaxControlToolkit;
    using System.Data.SqlClient;

    public partial class _Default : System.Web.UI.Page
    {

    protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
    {

    // Get selected values
    string make = DropDownList1.SelectedItem.Text;
    string model = DropDownList2.SelectedItem.Text;
    string color = DropDownList3.SelectedItem.Text;

    // Output result string based on which values are specified
    if (string.IsNullOrEmpty(make))
    {
    Label1.Text = "Please select a make.";
    }
    else if (string.IsNullOrEmpty(model))
    {
    Label1.Text = "Please select a model.";
    }
    else if (string.IsNullOrEmpty(color))
    {
    Label1.Text = "Please select a color.";
    }
    else
    {
    Label1.Text = string.Format("You have chosen a {0} {1} {2}. Nice car!", color, make, model);
    }

    }

    [WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static CascadingDropDownNameValue[] GetDropDownContentsPageMethod(string knownCategoryValues, string category)
    {
    return new CarsService().GetDropDownContents(knownCategoryValues, category);
    }


    }



    My problem is that when I use the following code to handle that event, the page just refreshes but doesn't try to post to my database, or even try to do anything, it just refreshes the page...

    protected void Button1_Click(object sender, EventArgs e)
    {

    string dropdown1 = DropDownList1.SelectedValue;
    string dropdown2 = DropDownList2.SelectedValue;
    string dropdown3 = DropDownList3.SelectedValue;

    string sql = "insert into used_equipment (project_owner, project_status, creation_date)\n";
    sql += "values(";
    sql += "'" + dropdown1 + "',";
    sql += "'" + dropdown2 + "',";
    sql += "'" + dropdown3 + "',";
    sql += "'" + MyCalander + "',";
    sql += "'" + radioValue + "'";
    sql += ")";


    conn.Open();
    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();
    conn.Close();
    }

    Anything obvious??? :confused::confused::confused:


  • Advertisement
  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    Don't have time to look at the code, but at this stage of the project it's no harm to print out stuff like:
    Response.Write("button clicked");
    to see if events are being triggered properly.


Advertisement