Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • ASP-Net-MVC-The CRUD-Part -2 Details Update and Delete

    • 0
    • 2
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 433
    Comment on it

    Hi Friends! I hope you'll be waiting for the next part of my previous CRUD article. So let's go for it.

    We'll perform the rest of the actions in following sequence.
    1-Details
    2-Edit/Update
    3-Delete

    Before moving to any method ,we need to define a method which is useful for each of the operation. Any Guesses?

    If we think about these methods and how they work,we'll find out that we need a user details by id or in our case,mobile. Because we need the details of a particular user to be deleted or updated. So what do we need here?

    A method in our "person" repository which can provide us the details of a user according to the mobile number supplied. So let's create it.

    In this article,I've assumed mobile number as my primary key(said supposed as no unique field check is there on the mobile number field). So we'll find details according to mobile number for our operations. Let's create a store procedure for the same.

    Create PROCEDURE [dbo].[showUserdetbyMobile]
    
        (
          @mobile nvarchar(50)
        )
    
    AS
    begin
        select * from [dbo].[user] where [mobile]=@mobile
        end
    

    Now that our stored procedure is created ,we'll use it in our repository class.

     public user showUserbyMobile(string mobile)
            {
                user User = new user();
                //SqlDataReader dr;
                DataTable dt;
                cmdparams.Clear();
                cmdparams["mobile"] = new SqlParameter("mobile", mobile);
                dt = br.readCmdDt("showUserdetbyMobile", cmdparams);
                User.mobile = Convert.ToString(dt.Rows[0]["mobile"]);
    
                User.password = Convert.ToString(dt.Rows[0]["password"]);
                User.lat = Convert.ToString(dt.Rows[0]["lat"]);
                User.longit = Convert.ToString(dt.Rows[0]["long"]);
                User.fname = Convert.ToString(dt.Rows[0]["f_name"]);
                User.lname = Convert.ToString(dt.Rows[0]["l_name"]);
                User.uname = Convert.ToString(dt.Rows[0]["u_name"]);
                User.address = Convert.ToString(dt.Rows[0]["Address"]);
                User.city = Convert.ToString(dt.Rows[0]["city"]);
                User.state = Convert.ToString(dt.Rows[0]["state"]);
                User.country = Convert.ToString(dt.Rows[0]["country"]);
                User.zip = Convert.ToString(dt.Rows[0]["zip"]);
                return User;
    
            }
    

    You can create the method as per your requirement or liking but return the "user" type because we need the details of the user to be stored in it. Now build the solution so that we can get our repository method in our controller.

    We'll show the details first. Open the user controller. We already have a Details controller written there. Now what? It looks pretty straight forward. Just follow the following steps.

    1-Instantiate the user(Model) object with the result of the our repository method
    2-Pass the model object as parameter in return view statement.
    3- And as we see that the showUserbyMobile method requires mobile,change the parameter of Details controller to string mobile.

    So your method looks something like following:-

     public ActionResult Details(string mobile)
            {
                user userdet = person.showUserbyMobile(mobile);
                return View(userdet);
            }
    

    I think we are all set now. Now run the project.
    Navigate to user/Index and click the "Details" button. What? An Error?
    What does the error say?

    Procedure or function 'showUserdetbyMobile' *expects parameter '@mobile', which was not supplied.*
    

    The parameter mobile is not being supplied from where? We've debugged all our code but it's the view which is not checked. Let's get to the "Details" button which is defined in Index.cshtml of user. Scroll to bottom and you'll see the code something like following:-

    alt text
    Fig 1-Action Link parameters

    When we see the highlighted area,we see three Actionlinks there. And they are with some commented code. We'll take care for the details part for now. The commented code is a place holder code for passing the id or the key(on the basis of which operations will be performed-primary key). So we need to modify the syntax according to our key "mobile";

    Now comment out the code and write it something like following:-

    mobile = item.mobile 
    

    I am sure you can understand the changes easily. One thing to note here. The left side of the syntax must match with the parameter in corresponding controller(spelling) other wise you'll get the same error again. I mean

    mobile(spelling in view page)==mobile(parameter spelling in corresponding controller method)
    

    Run the project and go to Index page of user controller. Now click the "Details" button again. This time you get the details of that particular user. That's not very fancy but it does fulfill the requirement of showing the user details.

    So we've got the concept about ids in action link. Copy the above syntax in all of the commented sections, as we'll be needing those ids in our edit and delete operations.

    As we've seen the details of user,we will focus on edit method now. We can see two Edit methods in user controller and we know that one is for post and other one is for get.

    So the "Edit with get "is used to retrieve the details to the edit view for editing. So we can just copy the Details controller code here so that only method names are different. Generate the view for the Edit method.

    Now run the project and click the edit button on the user list. You can see that the details are filled in to the textboxes.

    alt text
    Fig 2-Details for Editing

    If you press the save button now,you'll get an error again as the post type edit method is not written yet. So we need to create necessary things for posting an updated data to the database. The first one is? Yeah . Stored Procedure for update:-

    Create PROCEDURE [dbo].[updateUser]
    (
        @mobile nvarchar(MAX),
        @password nvarchar(MAX),
        @lat nvarchar(MAX) NULL,
        @longit nvarchar(MAX) NULL,
        @fname nvarchar(MAX) NULL,
        @lname nvarchar(MAX) NULL,
        @uname nvarchar(MAX) NULL,
        @address nvarchar(MAX) NULL,
        @city nvarchar(MAX) NULL,
        @state nvarchar(MAX) NULL,
        @country nvarchar(MAX) NULL,
        @zip nvarchar(MAX) NULL
        )
    
    AS
    begin
    
    
        update dbo.[user] set [password]=@password,[lat]=@lat,[long]=@longit,[f_name]=@fname,[l_name]=@lname,[u_name]=@uname,[Address]=@address,[city]=@city,[state]=@state,[country]=@country,[zip]=@zip where [mobile]=@mobile
        end
    

    Now we need to create a method in our repository. It'll look something like following:-

    public void updateUser(string mobile,user user)
           {
               cmdparams.Clear();
               cmdparams["mobile"] = new SqlParameter("mobile", user.mobile);
               cmdparams["password"] = new SqlParameter("password", user.password);
               cmdparams["lat"] = new SqlParameter("lat", user.lat);
               cmdparams["longit"] = new SqlParameter("longit", user.longit);
               cmdparams["fname"] = new SqlParameter("fname", user.fname);
               cmdparams["lname"] = new SqlParameter("lname", user.lname);
    
               cmdparams["uname"] = new SqlParameter("uname", user.uname);
               cmdparams["address"] = new SqlParameter("address", user.address);
               cmdparams["city"] = new SqlParameter("city", user.city);
               cmdparams["state"] = new SqlParameter("state", user.state);
               cmdparams["country"] = new SqlParameter("country", user.country);
               cmdparams["zip"] = new SqlParameter("zip", user.zip);
               br.cudCommand("updateUser", cmdparams);
           }
    

    Now build the solution so that we can use the method in our Edit controller for post.
    Now we need to modify controller according to our scenario. Remove the id and form collection objects and place mobile and user(mode) objects as parameter. Now simply call the update method in the repository. Your Edit method should look something like following:-

     [HttpPost]
            public ActionResult Edit(string mobile, user user)
            {
                try
                {
                    // TODO: Add update logic here
                    person.updateUser(mobile, user);
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    

    Now run the project. Go an edit any detail. You see that you are able to update the detail of a user. Technically the mobile number should not be shown in textbox but this is just a representation of CRUD,so we can leave it for now as we are focusing on CRUD only.

    So we've reached to CRU of CRUD. And project is running except one glitch. We can't move from details page to edit page by clicking "Edit" button. Got an idea?Yes,we've solved that previously. It's just the id problem in Details.cshtml. We need put the syntax

    mobile=Model.mobile 
    

    in Edit action link. And the problem is solved. Hurray!!!

    The last thing left is the "Delete" operation. The steps will be almost same. So make a stored procedure for that:-

    Create PROCEDURE [dbo].[deleteUser]
    (
        @mobile nvarchar(MAX)
    
        )
    
    AS
    begin
        delete from dbo.[user] where [mobile]=@mobile
        end
    

    Now the repository method:-

    public void deleteUser(string mobile,user user)
            {
                cmdparams.Clear();
                cmdparams["mobile"] = new SqlParameter("mobile", user.mobile);
    
                br.cudCommand("deleteUser", cmdparams);
            }
    

    Build the solution so that the method can be used in the controller. In the get method for Delete we need to write the same code as we wrote in get method of update. Generate the view for the method and run the project.

    When you click the "Delete" method of the list,you find a screen similar to "Details" but we haven't written the method for deletion yet so we'll get an error if we try to press the "Delete" button here.

    Use the repository method in the post type controller of "Delete". Your method should look something like following:-

     [HttpPost]
            public ActionResult Delete(user user)
            {
                try
                {
                    // TODO: Add delete logic here
                    person.deleteUser(user.mobile);
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    

    Now run the project and try deleting something. The record will be deleted and you'll be redirected to the list.

    So we've completed our CRUD functionality tutorial. This example in this article may not fit on the scale of validation and some coding conventions,but it does perform the CRUD functionality perfectly. The validations for unique mobile number etc will be covered in subsequent articles in detail.

    I'll be telling you the same CRUD functionality with Entity Framework too,but I am sure that you can figure it out easily.

    So practice with the concept and try improving this code with more validations and try building your own concept of CRUD.

    Happy Coding:-)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: