Tuesday, 26 May 2015

Editing Modal and Update modal in Asp.Net MVC

In previous article we learn how to create a business object modal and how to insert data in database .In this article we will learn how to Edit data modal on edit click event . Before proceeding this tutorial go to this


Editing  Data modal
We want that when we click on EDIT link it should render to the Index Action method of StudentController , with specific ID .
So for that first create a Action method for this and create a view for editing these data.
Action method will be like
[HttpGet]
        public ActionResult Edit(int ID)
        {
            Student student = new Student();
           
            BusinessLogic BL = new BusinessLogic();
            Student _student = BL.student.Where(c => c.StudentID == ID).SingleOrDefault();
            return View(student);
        }


After that we need for a View  , so create a Edit View by right click on this action method and add a view


Delete the following script from the view
@section Scripts 
{
    @Scripts.Render(
"~/bundles/jqueryval")
}

After that View Code will be like following
@model BusinessLayer.Student

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<div style = "font-family:Arial>
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Student</legend>

        @Html.HiddenFor(model => model.StudentID)

        <div class="editor-label">
            @Html.LabelFor(model => model.StudentName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.StudentName)
            @Html.ValidationMessageFor(model => model.StudentName)
        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Gender)
        </div>
        <div class="editor-field">
           
            @Html.DropDownList("Gender", new List<SelectListItem>
            {
            new SelectListItem { Text = "Male", Value="Male" },
            new SelectListItem { Text = "Female", Value="Female" }
            }, "Select Gender")

           
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.StudentClass)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.StudentClass)
            @Html.ValidationMessageFor(model => model.StudentClass)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
</div>




Run you application you will see All the data from database in grid like this

When we will click on Edit link it will redirect to EDIT View and look like that

Here you edit the data and click on Save button you will see updated value
Updating  Datamodal
Step(1) : -Now if we click on Save button it gives error because The edit method is using “[HttpGet]” attribute means that this action result Edit method is only accept get request.
For updating the Edit value in database, first create the stored procedure for update ion, So Stored procedure will be like following

Create procedure UpdateStudentInfo     
@StudentID int,
@StudentName nvarchar(50),     
@Gender nvarchar (10),     
@SchoolName nvarchar (50)
as     
Begin     
 Update StudentInfo Set
 StudentName = @StudentName,
 Gender = @Gender,
 SchoolName = @SchoolName
 Where StudentID = @StudentID
End

Step(2): Now go to the BussinessLayer Library project and in BusinessLogic.cs class add a save function, For saving the data into databse.
public void SaveStudentInfo(Student student)
        {
            string connectionString =
                    ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("UpdateStudentInfo", con);
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter studentId = new SqlParameter();
                studentId.ParameterName = "@StudentID";
                studentId.Value = student.StudentID;
                cmd.Parameters.Add(studentId);

                SqlParameter studentName = new SqlParameter();
                studentName.ParameterName = "@StudentName";
                studentName.Value = student.StudentName;
                cmd.Parameters.Add(studentName);

                SqlParameter Gender = new SqlParameter();
                Gender.ParameterName = "@Gender";
                Gender.Value = student.Gender;
                cmd.Parameters.Add(Gender);

                SqlParameter schoolname = new SqlParameter();
                schoolname.ParameterName = "@SchoolName";
                schoolname.Value = student.StudentClass;
                cmd.Parameters.Add(schoolname);              

                con.Open();
                cmd.ExecuteNonQuery();
            }

        }


Step(3): - Go to Student Controller and add a Edit post method for updating the value. Method code will like following
[HttpPost]
        public ActionResult Edit()
        {
            if (ModelState.IsValid)
            {
                Student student = new Student();
                UpdateModel<Student>(student);
                BusinessLogic BL = new BusinessLogic();

                BL.SaveStudentInfo(student);
                return RedirectToAction("Index");
            }
            return View();
        }


Step(4): Now run your application and click on edit button change the value and save it .. you will see updated value.


After saving edited value will look like this


Sunday, 24 May 2015

UpdateModal and TryUpdateModal in Asp.Net MVC

Here we will learn Update Modal and try update modal in asp.net MVC. Before coming to this tutorial go through Insert data into database .
In previous tutorial we learned how to insert data into database in MVC, so for that we used “FormCollection parameter” , we also did this with passing parameter for all the modal properties in function.
Except these two things we can pass “Student” class object also as a parameter in Create controller action method for Post request, See following code.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BusinessLayer;

namespace MvcApplication2.Controllers
{
    public class StudentController : Controller
    {
        public ActionResult Index()
        {
            BusinessLogic BL = new BusinessLogic();

            List<Student> student = BL.student.ToList();
            return View(student);
        }

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }    

        [HttpPost]
        public ActionResult Create(Student student)
        {
            //Student student = new Student();           
            //student.StudentName = formCollection["StudentName"];
            //student.Gender = formCollection["Gender"];
            //student.StudentClass = formCollection["StudentClass"];           

            BusinessLogic BL =new BusinessLogic();

            BL.InsertStudentDetail(student);
            return RedirectToAction("Index");
        }

    }
}



Now if you will run your application and you will click on New Create and you will fill value in screen then it will update as it was working with “Formcollection method”.
Here we can use “ModelState” parameter for checking Validation in modal class , if we use this ModalState then Create  controller post method will we like following
[HttpPost]
        public ActionResult Create(Student student)
        {

            if (ModelState.IsValid)
            {
                BusinessLogic BL = new BusinessLogic();

                BL.InsertStudentDetail(student);
                return RedirectToAction("Index");
            }
            return View();
        }


This ModalState is used with “IsValid” Boolean property for checking either all the modal properties is valid or not.
Use Update Modal Function
Above Create Controller action method of Post request can be written with the “UpdateModal
Then the function will be
[HttpPost]
        public ActionResult Create()
        {           
            if (ModelState.IsValid)
            {
                Student student = new Student();

                UpdateModel<Student>(student);

                BusinessLogic BL = new BusinessLogic();

                BL.InsertStudentDetail(student);
                return RedirectToAction("Index");
            }
            return View();
        }
At this time if we run our application then it will give a compilation error that
Error 1       Type 'MvcApplication2.Controllers.StudentController' already defines a member called 'Create' with the same parameter types    
So Get rid of this problem we have to change the name for this create method , So we give this method name as Create_Post method. Now if we run this application and click on Create button then it will not render to the Create view because we changed the Action method , And as we no action method name and view name should be same.
So Get rid of this problem also we use “ActionName” Attribute .So code will be
[HttpPost]
        [ActionName("Create")]
        public ActionResult Create_Post()
        {           
            if (ModelState.IsValid)
            {
                Student student = new Student();
                UpdateModel<Student>(student);
                BusinessLogic BL = new BusinessLogic();

                BL.InsertStudentDetail(student);
                return RedirectToAction("Index");
            }
            return View();
        }


Run your application and insert new student record into the database.
TryUpdateModal function
First make the changes in Create_post()method like following code
[HttpPost]
        [ActionName("Create")]
        public ActionResult Create_Post()
        {           
                Student student = new Student();
                UpdateModel<Student>(student);
                BusinessLogic BL = new BusinessLogic();

            if (ModelState.IsValid)
            {

                BL.InsertStudentDetail(student);
                return RedirectToAction("Index");
            }
            return View();
        }


Suppose while inserting data into database if we not fill any value for name, gender, school  name then we click on Create button then it will error that “ its expected name, gender, school name.
So make these properties as option change database stored procedure

Alter procedure insertStdDetail     
@StudentName nvarchar(50) = null,    

@Gender 
nvarchar(10) = null,     
@SchoolName 
nvarchar (50) = null
as    
Begin    
 Insert into StudentInfo (Name, Gender, SchoolName)    
 Values (@StudentName, @Gender, @SchoolName)    

End

Now if we insert data into database it will insert NULL data into database, So if we want data into database we have to make required properties , For that we can use “required attribute” which present in “System.ComponentModel.DataAnnotations namespace”.
So for this in BusinessLayer project we have add “EntityFramework” assembly for getting Following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace BusinessLayer
{
    public class Student
    {
        public int StudentID { get; set; }

        [Required]

        public string StudentName { 
get; set; }
        public string Gender { 
get; set; }
        [Required]

        public string SchoolName { 
get; set; }

    }
}

Now run this application and without entry data click on Create button we will get error like
The model of type 'BusinessLayer.Employee' could not be updated.”. This error come from the updateModal trigger.
Now let’s change this update modal in “TryUpdateModal” in Create_Post Action method of StudentController.
[HttpPost]
[ActionName("Create")]

public ActionResult Create_Post()
{
    BusinessLogic BL =     
new BusinessLogic ();
Student student = new Student();

    TryUpdateModel(student);
    if (ModelState.IsValid)

    {
   UpdateModel<Student>(student);             

   BL.InsertStudentDetail(student);

     
        return RedirectToAction("Index");

    }
    else

    {
        return View();

    }
}

If Now you will run your application without entry data it will not give exception.

So the difference b/w “updatemodal” and “tryUpdateModal” is that update modal doesn’t handle null and give error while TryUpdateModal handle this error.

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...