Operating data in ASP.net 2.0 23: Based on user restrictions on the modification of data _ self-study process

Source: Internet
Author: User

Introduction

Many web programs support user accounts, depending on the user to provide different options, reports and other functions. For example, in our tutorial, we want to allow some accounts of the vendor company to log on to the site and update their products-including the product name and unit price, and perhaps the supplier's information, such as their company name, address, and contact information, and so on. In addition, we might want to include some accounts for our own company users so that they can log in and make changes to the product information, such as stock prices, level adjustments, and so on. Our web programs can also allow anonymous logons, but only allow those users to browse the data. and contains a system user, through to the ASP.net page data control can carry on the data to increase, change, delete.

In this tutorial, we will examine how to dynamically adjust the ability to modify data based on different access users. Further, we create a new page that displays vendor information through an editable DetailsView and a GridView control that lists the products provided by the vendor. If visitors come from our company, they can view any vendor information, edit their address, and edit the product information provided by any one of the suppliers. However, if a user comes from a specific company, they can only view and modify their own company's address information, or modify their information about goods that are not out of stock.

Figure 1: A user from our company can edit any one of the vendor's information

Figure 2: A company from a vendor who can only view and edit their own information

Let's get started!

Note: The ASP.NET 2.0 Membership system provides a standard, scalable platform to create, manage, and authenticate user accounts. Considering that the membership system is beyond the content of this article, this article will assume that anonymous users have passed the membership system, they can be considered to be from a specific supplier or our company. For more membership content, refer to my ASP.net 2.0 membership, Roles, Profiles article series.

First step: Allow users to specify their access rights

In a real-world Web application, a user's account information already contains a recognition that they are from our company or supplier, and that information can be accessed in asp.net after the user has logged in. This information can be obtained through the ASP.net 2.0 role system, as a file system or other business user account information.

Since this tutorial is a demonstration of the ability to adjust data modifications for different logged-in users, and not to highlight the use of the ASP.net 2.0 membership,roles, and Profile system, we will use a very simple mechanism to determine the user's ability to access the page-through a drop-down box, Users can choose to view or modify any one vendor's information, or as a vendor, to view and modify their own information. If the user uses the default to view and modify any vendor information, she will page through all the vendors, edit their address information, and edit the name or unit price of a selected vendor's product. If you choose to view and edit only one vendor's information, she can only view the vendor's product details and update the name and unit price of those products that have not expired.

Next we're going to create a new DropDownList and populate it with system vendor information data. Open the Userlevelaccess.aspx page under the EditInsertDelete folder, add a DropDownList control, set its id attribute to suppliers, and bind to a allsuppliersdatasource named Objec Tdatasource control.

Figure 3: Creating a ObjectDataSource control named Allsuppliersdatasource

Because we want DropDownList to display all the suppliers, we configure ObjectDataSource to invoke the Getsuppliers () method in the Suppliersbll class. Also, make sure that the update () method of the control is mapped to the Updatesupplieraddress method of the Suppliersbll class, and that the ObjectDataSource control is used by the DetailsView control in the next step. After you finish setting up the ObjectDataSource, complete the Set Suppliers Drop-down control so that each of its ListItem displays the data member as CompanyName and the value of the data member is SupplierID.

Figure 4: Configuring Suppliers DropDownList to use CompanyName and SupplierID data members

Here, this DropDownList lists the names of all the vendors in the database. However, we also need to add a "show/Edit all Vendors" option to the dropdown box. You can do this by setting the Appenddatabounditem property of the Suppliers Drop-down box to true and adding a ListItem, setting its Text property to show/edit all vendors, and the Value property to. These can be added by directly declaring markup language or by clicking the Item property of the Drop-down box in the designer of the property window.

  Note: You can go back to the tutorial "using DropDownList filtered master/from report" for a detailed discussion of adding the Show All option in a Drop-down box. By setting the AppendDataBoundItems property and adding ListItem, the DropDownList declaration is marked as follows:

<asp:dropdownlist id= "Suppliers" runat= "Server" appenddatabounditems= "True"
  datasourceid= " Allsuppliersdatasource "datatextfield=" CompanyName "
  datavaluefield=" SupplierID ">
  <asp:listitem Value= "-1" >show/edit all suppliers</asp:listitem>
</asp:DropDownList>

Figure 5 is a screenshot of the current operation in the browser.

Figure 5: The ListItem suppliers dropdown box with a "show all" and each of the other vendor names

Since we want users to change their selections and update the user interface immediately, we need to set the AutoPostBack property value of the Suppliers dropdown box to true. In the second step we will create a DetailsView control to display the vendor details that are displayed based on the user selection. Then, in the third step, we will create a SelectedIndexChanged event handler for the dropdown box, in which we will bind the specific vendor information to the DetailsView control based on the current selection.

Step Two: Add a DetailsView control

Let's use the DetailsView control to display vendor information. For users who can view and edit all vendor information, DetailsView will support paging and allow users to view each vendor profile one at a time. If the user is one of the vendors, then DetailsView will display only the current vendor information and will not contain the paging interface. In both cases, DetailsView will allow the user to edit the address, city, and country values of the vendor that can be accessed.

Add a DetailsView under the Suppliers Drop-down box, set its id attribute to Supplierdetails, and then bind it to the Allsuppliersdatasource ObjectDataSource control you created earlier. After that, open the enable paging and the Enable Editing multiple-selection boxes in the DetailsView smart tag.

  Note: If you do not see the Enable Edit attribute in the DetailsView tag code, it is because you do not have the update () method of the ObjectDataSource

The Updatesupplieraddress method that is bound to the SUPPLIERSBLL class. Take a little bit of the event back to the past and reset it, and then come back and see the Enable Edit property. Because the Updatesupplieraddress method of the Suppliersbll class allows only four parameters-supplierid,address,city and country, Need to modify DetailsView BoundFields let CompanyName and phone two BoundFields is read-only. Also, remove SupplierID this BoundField completely. Finally, the Allsuppliersdatasource control already contains a OldValuesParameterFormatString property with a value of original_{0}. Take some time to remove it completely or modify it to the default value of {0}. By supplierdetails this DetailsView control and the settings for Allsuppliersdatasource this ObjectDataSource control, our code looks like this:

<asp:objectdatasource id= "Allsuppliersdatasource" runat= "selectmethod=" Getsuppliers "TypeName=" Suppliersbll "updatemethod=" updatesupplieraddress "> <UpdateParameters> <asp:parameter name=" SupplierID "Type=" Int32 "/> <asp:parameter name=" Address "type=" String "/> <asp:parameter" City "Name=" type= ng "/> <asp:parameter name=" Country "type=" String "/> </UpdateParameters> &LT;/ASP:OBJECTDATASOURCE&G
T <asp:detailsview id= "supplierdetails" runat= "Server" allowpaging= "True" autogeneraterows= "False" datakeynames= " SupplierID "datasourceid=" Allsuppliersdatasource "> <Fields> <asp:boundfield datafield=" CompanyName "he Adertext= "Company" readonly= "True" sortexpression= "CompanyName"/> <asp:boundfield "Address" datafield= dertext= "Address" sortexpression= ' address '/> <asp:boundfield datafield= "City" headertext= "City" Sor texpression= "City"/> <asp:bouNdfield datafield= "Country" headertext= "Country" sortexpression= "Country"/> <asp:boundfield "datafield=" Ph One "headertext=" Phone "readonly=" true "sortexpression=" Phone "/> <asp:commandfield showeditbutton=" True "
 /> </Fields> </asp:DetailsView>

Regardless of what is selected in the Suppliers dropdown box, DetailsView can be paged, and the selected vendor's address information can also be updated. (See Figure 6)

Figure 6: Any vendor's information can be viewed and his address can be updated.

Step three: Show only vendor information that is selected

Our pages can now see all of the vendor's information regardless of which vendor is selected from the Suppliers drop-down box. To display only the selected vendor information, we need to add another ObjectDataSource to the page to get a specific vendor information.

Add a new ObjectDataSource control to the page named Singlesupplierdatasource. In the tag smart tag, click the Configure Data Source link to use the Getsupplierbysupplierid (SupplierID) method of the Suppliersbll class. As with Allsuppliersdatasource this control, the update () method of the Singlesupplierdatasource control is pointed to the Updatesupplieradress method of the Suppliersbll class.

Figure 7: Configuring the Singlesupplierdatasource ObjectDataSource Control and using the Getsupplierbysupplierid (SupplierID) method

Next, we are prompted to specify the argument source for the SupplierID parameter of the Getsupplierbysupplierid (SupplierID) method. Because we want to display the information from the supplier selected from the dropdown box, here we select the SelectedValue attribute of the Suppliers dropdown box as the parameter source.

Figure 8: Using the Suppliers drop-down box as the SupplierID parameter source

Even if we add a second ObjectDataSource, the current DetailsView is still using Allsuppliersdatasource this ObjectDataSource control. We need to add some logic to adjust the use of the data source according to the vendors in different suppliers. To do this, you can add a SelectedIndexChanged event processor to the Suppliers dropdown box. You can do this by double-clicking the Drop-down box in the designer in the simplest way. This event handler needs to decide what data source to use, and it needs to rebind the data channel DetailsView control. Here is the code to complete the function:

 protected void Suppliers_selectedindexchanged (object sender, EventArgs e) {if (supp Liers. SelectedValue = = "-1") {//the "Show/edit all" option has been selected Supplierdetails.datasourceid = "Allsupp
    Liersdatasource ";
  Reset the page index to show the Supplierdetails.pageindex = 0;
  else//The user picked a particular supplier Supplierdetails.datasourceid = "Singlesupplierdatasource";
  Ensure that's DetailsView is in read-only mode Supplierdetails.changemode (detailsviewmode.readonly);
Need to "Refresh" the DetailsView supplierdetails.databind (); }

This event handler is triggered by whether to select Show/edit all vendors. If selected, it sets the DataSourceID of the DetailsView control supplierdetails as the Allsuppliersdatasource control. And by specifying pageindex as 0来, the user is given the first record of these vendors. However, if the user chooses a specific vendor from the dropdown box, the DetailsView DataSourceID will be set to Singlesuppliersdatasource. Regardless of which data source is used, Suppliersdetails is set to read-only mode, and the DetailsView data is rebind by calling the DataBind () method of the Suppliersdetails control.

With this event handler, DetailsView can now display the selected vendor information, unless "show/edit All Suppliers" is selected, so that all vendors can be browsed through pagination. Figure 9 shows a page with "show/Edit All Suppliers" selected, note the implementation of the paging interface, and allow users to access and update vendor information. Figure 10 shows the selected Ma Maison vendor information. In this case, only the information for Ma Maison can be browsed and edited.

Figure 9: All vendor information can be browsed and edited

Figure 10: Only the selected vendor information can be browsed and edited

  Note: For this tutorial, the EnableViewState of the DropDownList and DetailsView controls must be set to the default true. This is because changing the DataSourceID attributes of DropDownList's SelectedIndex and DetailsView must be recorded at the time of return.

Step Fourth: List vendor information in an editable GridView

With the completion of the DetailsView, our next step is to provide a GridView that can be edited based on the selected vendor. This GridView control should only allow editing of the ProductName and QuantityPerUnit properties. In addition, if the user is a specific vendor and accesses the page, it should allow him to update products that are not obsolete. To implement these we first need to add an overloaded Updateproducts method to the Productbll class, let it use Productid,productname, and quantityperunit as input parameters. We've done similar things in the previous tutorials, so here's just a look at the code that needs to be added to the PRODUCTSBLL class:

 [System.ComponentModel.DataObjectMethodAttribute ( System.ComponentModel.DataObjectMethodType.Update, false)] public bool UpdateProduct (string productName, String
  QuantityPerUnit, int productID) {northwind.productsdatatable products = Adapter.getproductbyproductid (ProductID); if (products.
  Count = = 0)//No matching record found and return false to false;
  Northwind.productsrow product = Products[0]; Product.
  ProductName = ProductName; if (QuantityPerUnit = = null) product.
  Setquantityperunitnull (); else product.
  QuantityPerUnit = QuantityPerUnit;
  Update the product record int rowsaffected = adapter.update (product);
Return true if precisely one row is updated, otherwise false return rowsaffected = = 1; }

With this overloaded method, we can start adding the GridView control and the associated ObjectDataSource Control. Add a GridView control to the page, set its ID property to Productbysupplier, and then configure it to use the new ObjectDataSource control named Productbysupplierdatasource. Because we want to make the GridView display those products by selecting a vendor, we need to use the Getproductsbysupplierid (SupplierID) method of the Productbll class. It is also necessary to map the overloaded method UpdateProduct just added to the ObjectDataSource Update () method.

Figure 11: Configuring ObjectDataSource using the added UpdateProduct overload method

Next we are prompted to select the parameter source for the SupplierID input parameter of the Getproductsbysupplierid (SupplierID) method. Because we want to display the supplier's product information in the DetailsView, we use the SelectedValue property of the DetailsView control as the parameter source suppliersdetails.

Figure 12: Using the SelectedValue property of the Suppliersdetails DetailsView control as the parameter source

Back to the GridView, remove Productname,quantityperunit, and discontinued other members, and Mark discontinued CheckBoxField as read-only. Also, check the Enable editing option in the GridView smart tag. After these changes are made, the GridView and ObjectDataSource declaration tags should resemble the following:

<asp:gridview id= "Productsbysupplier" runat= "Server" autogeneratecolumns= "False" datakeynames= "ProductID"
    Datasourceid= "Productsbysupplierdatasource" > <Columns> <asp:commandfield showeditbutton= "True"/> <asp:boundfield datafield= "ProductName" headertext= "Product" sortexpression= "ProductName"/> <asp:boun Dfield datafield= "QuantityPerUnit" headertext= "Qty/unit" sortexpression= "QuantityPerUnit"/> <asp:CheckBox Field datafield= "discontinued" headertext= "discontinued" readonly= "True" sortexpression= "discontinued"/> </
  columns> </asp:GridView> <asp:objectdatasource id= "Productsbysupplierdatasource" runat= "Server" oldvaluesparameterformatstring= "original_{0}" Typename= "Productsbll" selectmethod= "GetProductsBySupplierID"
    updatemethod= "UpdateProduct" > <UpdateParameters> <asp:parameter name= "ProductName" type= "String"/> <asp:parameter name= "QuantityPerUnit" type= "String"/> <asp:parameter name= "ProductID" type= "Int32"/> </UpdateParameters> <SelectParameters> <asp:controlparameter controlid= "Supplierdetails" name= "SupplierID" propertyname= "SelectedValue" Type= "Int32"/&
  Gt

 </SelectParameters> </asp:ObjectDataSource>

As in the previous ObjectDataSource, the oldvaluesparameterformatstring of this ObjectDataSource control is set to original_{0} and there is a problem updating the product name and its unit price. You can either drop this property from the declaration or set its value to the default {0}. After the configuration is complete, our page can now display the product information of the selected vendor in the GridView (see Figure 13). Now, the name of any product and the unit price can be edited and updated. Then, we need to update the code logic to ensure that the users associated with the specified vendor filter those products that have been discarded. We will implement it at the end of step fourth.

Figure 13: The selected vendor's product is displayed

  Note: By adding an editable GridView control, in the SelectedIndexChanged event handler of the Suppliers dropdown box, we should update the GridView back to read-only state. Otherwise, if you replace a vendor while editing a product information, an index of the corresponding GridView will maintain the GridView editable state. To avoid this kind of thing, you can simply set the Editindex property of the GridView to-1 in selectedindexchanged things.

Fifth step: Do not allow editing of obsolete products when "show/edit all Suppliers" is not selected

Although the Productsbysupplier GridView is fully functional, it currently provides too many access rights for users from a specified vendor. According to our business rules, users are not able to update obsolete products. To do this, when a user from a given vendor accesses the page, we hide the edit button in front of these discarded products in the GridView.

The

Creates a new event handler for the RowDataBound event of the GridView. In the event handler we need to determine whether the user is associated with a vendor, and for the tutorial we can decide-if not-1-that the user is associated with the current vendor by suppliers the dropdown box. For some users, we need to decide whether the product has been discarded. We can go through E. Row.dataitem property to get a Productrow instance bound to the GridView, as we mentioned in the walkthrough's Footer display summary information tutorial. If the product expires, we can use the technology discussed in the previous tutorial-add client confirmation to delete data, get a reference to an Edit button in the Commandfild of the GridView, and once we get that reference, we can hide or remove the button.

protected void Productsbysupplier_rowdatabound (object sender, GridViewRowEventArgs e)
{
  if (E.row.rowtype = = Datacontrolrowtype.datarow)
  {
    //Is this a supplier-specific user?
    if (Suppliers.selectedvalue!= "-1")
    {
      //Get a reference to the Productrow
      Northwind.productsrow product =
    (Northwind.productsrow) (System.Data.DataRowView) e.row.dataitem). Row;
      Is this product discontinued?
      if (product. Discontinued)
      {
        //Get a reference to the Edit LinkButton
        LinkButton Editbutton = (LinkButton) e.row.cells [0]. Controls[0];
        Hide the Edit button
        editbutton.visible = false;}}


In the event handler, when a user from a specified vendor accesses the page, the discarded products are not editable because the edit buttons for these products are no longer visible. For example, Chef Anton's gumbo mix is an obsolete product for New Orleans Cajun delights suppliers. When users of this vendor visit this page, the Edit button for this product is not visible (see Figure 14). However, when you use the Show/edit all vendors access page, the Edit button is visible (see Figure 15).

Figure 14: The Edit button for the Chef Anton ' Gumbo mix is hidden for the specified vendor user

Figure 15: The Edit button for the Chef Anton ' gumbo mix is visible for the show/edit all vendors User

Checking access rights in the business logic layer

In this tutorial, ASP. NET enables users to access that information and which products he can update by processing logic. Conceptually, these logic can also be completed in the business logic. For example, the Getsuppliers () method in the Suppliersbll class can contain a test to ensure that the currently logged-on user is not associated with a specified vendor. Similarly, the Updatesupplieraddress method can add a test to ensure that the currently logged-on user can either be from our company (and therefore can update all the vendor's address data) or be related to a specific vendor, and can only update his data. Here I will not include any detection code for the business logic layer, because in the tutorial, the user's permissions are determined by the page's Drop-down box, and the class code of the business logic layer is inaccessible. When using a member system or an authentication mode provided by ASP.net (such as Windows authentication), the information and role information of the current logged-on user can be accessed through the business logic layer, so that the permissions can be judged at both the presentation level and the business layer in that case.

Summarize

Most of the sites that provide accounts need to customize different data modification interfaces based on the logged-in user. Administrators may be able to delete or edit any records, and users without administrative privileges may be restricted to updating or deleting only the data they create themselves. In either case, the data Web control, ObjectDataSource, and business logic layer classes can be used to extend the Add-delete feature based on the logged-in user. In this tutorial, we see if you want to restrict the display and editing of data based on whether a user is associated with a vendor or a member of our company.

This tutorial summarizes the use of Gridview,detailsview and FormView controls to add, update, and delete data. Starting with the next article, we'll focus on the feature support for adding paging and sorting.

I wish you a happy programming!

Author Introduction

Scott Mitchell, with six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. Scott is an independent technical consultant, trainer, writer, recently completed a new book to be published by Sams Press, proficient in asp.net 2.0 within 24 hours. His contact email is mitchell@4guysfromrolla.com, or he can contact him through his blog Http://ScottOnWriting.NET.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.