Showing posts with label sumit blog. Show all posts
Showing posts with label sumit blog. Show all posts

Monday, July 21, 2014

DropDownList in ASP.Net MVC 4

DropDownList in ASP.Net MVC 4

In this blog, I am going to explain how to create dropdownlist in the asp.net mvc 4.

Step 1

First create an empty asp.net mvc  4 web application and add a model class “Game” like this:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DropDownListMvcApp.Models
{
    public class Game
    {
       private List<SelectListItem> _game = new List<SelectListItem>();

       [Required(ErrorMessage="Please select you favorite game")]
       public string SelectedGame { get; set; }

       public List<SelectListItem> GameList
       {
           get
           {
               _game.Add(new SelectListItem() { Text = "Cricket", Value="Cricket"});
               _game.Add(new SelectListItem() { Text = "Hockey", Value = "Hockey" });
               _game.Add(new SelectListItem() { Text = "Football", Value = "Football" });
               return _game;
           }
       }
    }
}

Step 2

Now add a controller to the project named “HomeController” to the project and write below code to it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DropDownListMvcApp.Models;

namespace DropDownListMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View(new Game());
        }

        [HttpPost]
        public ActionResult Index(Game game)
        {
            if (ModelState.IsValid)
            {
                return View("Result", game);
            }
            else
            {
                return View(game);
            }
           
        }

    }
}

Step 3

Now add the view to the project named “Index” and write the below code in it:
@model DropDownListMvcApp.Models.Game

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<script type="text/javascript">
    function selectedIndexChanged() {
    }
</script>

<div>
    <div>
        @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        {
            <label>Favourite Game : </label>
            @Html.DropDownListFor(m => m.SelectedGame, new SelectList(Model.GameList, "Value", "Text"), "Select Game", new { id = "gameDropDownList", onchange = "selectedIndexChanged()" })
            @Html.ValidationMessageFor(m => m.SelectedGame)

            <br />
            <input type="submit" value="Submit" />
        }
    </div>
</div>

Now add another view to the project named “Result” to show the selected value of the dropdownlist and write the below code in it:
                @{
    ViewBag.Title = "Result";
}

<h2>Result</h2>

<div>
    @ViewData.Model.SelectedGame
</div>

Your solution explorer must look like this:


Output

Now run the application:



Click on submit will show you error like this:




Select your favourite game and click on submit:





Thank you for reading this article, please put your valuable comment or any suggestion/question in the comment box. 





Saturday, July 12, 2014

CRUD Operation Using Entity Framework in ASP.Net MVC 4

CRUD Operation Using Entity Framework in ASP.Net MVC 4

In this blog, I am going to tell how to perform create, read, update and delete operations using entity framework in asp.net mvc 4.

Step -1

First create a table named “StudentInformation” in the database like this:












And enter some dummy data in the table.

Now create an asp.net mvc 4 web application and install the entity framework in your project like this:















































Step -2

Now add a model class named “StudentInformation” to the project and write the below code in it:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace CRUDWithEntityFramework.Models
{
    [Table("StudentInformation")]  // Table Name
    public class StudentInformation
    {
        [Key] //Primary Key
        public int StudentId { get; set; }

        [Required(ErrorMessage = "Name is mandatory")]
        [Display(Name="NAME")]
        public string Name { get; set; }

        [Required(ErrorMessage="Age is mandatory")]
        [Display(Name="AGE")]
        public string Age { get; set; }

        [Required(ErrorMessage="Address is manadatory")]
        [Display(Name="ADDRESS")]
        public string Address { get; set; }

        [Required(ErrorMessage="Course is mandatory")]
        [Display(Name="COURSE")]
        public string Course { get; set; }
    }
}

Step-3

Next we need to create a DBContext object named “StudentDBContext” that will be responsible for performing all the CRUD operations on “StudentInformation” model class.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace CRUDWithEntityFramework.Models
{
    public class StudentDBContext : DbContext
    {
        public DbSet<StudentInformation> student { get; set; }
    }
}

Step -4

Create a connection string in the web.config like this:
<connectionStrings>
    <add name="StudentDBContext" connectionString="Data Source=DELL-PC; Initial Catalog=StudentDB; Integrated Security = true;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

The important thing to notice here is that the name of the connectionString is same as the DbContext class that we have created. If we keep the name of the connectionString same as the DbContext class the corresponding DbContext class will use the connectionString to persist the data, but this is also flexible so that we have the possiblity of giving custom names to the connectionStrings.

Step -5

Now create a controller class named “StudentController” and it will perform the CRUD operations on the “StudentInformation” entity and write the below in it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CRUDWithEntityFramework.Models;

namespace CRUDWithEntityFramework.Controllers
{
    public class StudentController : Controller
    {
        StudentDBContext context = new StudentDBContext();

        public ActionResult Index()
        {
            List<StudentInformation> studentList = context.student.ToList();
            return View(studentList);
        }

        public ActionResult Details(int id)
        {
            StudentInformation student = context.student.SingleOrDefault(m => m.StudentId == id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(StudentInformation student)
        {
            if (ModelState.IsValid)
            {
                context.student.Add(student);
                context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }

        public ActionResult Edit(int id)
        {
            StudentInformation student = context.student.Single(m => m.StudentId == id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        [HttpPost]
        public ActionResult Edit(int id, StudentInformation student)
        {
            StudentInformation _student = context.student.Single(m=>m.StudentId == id);
            if (ModelState.IsValid)
            {
                _student.Name = student.Name;
                _student.Age = student.Age;
                _student.Address = student.Address;
                _student.Course = student.Course;

                context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
         }

        public ActionResult Delete(int id)
        {
            StudentInformation student = context.student.Single(m=>m.StudentId == id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        [HttpPost]
        public ActionResult Delete(int id, StudentInformation student)
        {
            StudentInformation _student = context.student.Single(m=>m.StudentId == id);
            context.student.Remove(_student);
            context.SaveChanges();
            return RedirectToAction("Index");
        }

    }
}

Step -6

Now add the view for list, details, create, edit and delete to the project – these views will be strongly typed and scaffold views.


Index View – To show the list of students






















Create View – To add a new student.























Details View – To show the details of a particular student.
























Edit View – To edit/update the details of a particular student.























Delete View – To delete a particular student.





















As you can see that using the Scaffold template option – the view is created for you and don’t have to write anything in the view by itself.

Step-7

Now open the “RouteConfig.cs” file in the App_Start folder and change the name of the controller from home to Student like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace CRUDWithEntityFramework
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

After doing all the above things your solution explorer will look like this:



























Output

Now build the application and run it:

First you will see that a list of students:












Now click Create new
























Now click on Edit
























Now click on Details




















Now click on Delete



















Thank you for reading this article, please put your valuable comment or any suggestion/question in the comment box.