Monday, 23 December 2013

Bind Country,state,city in DropdownList in MVC4





Description:-

            In this Example I Explain that How to Bind Country,State and City in DropdownList From Sqlserver Database in MVC4. we Already Explain that How to Bind dropdownList in asp.Net but in MVC that is diiferant way to Bind Country,State in  DropdownList

Here we Create a Action Result Create to Fetch data from the Database and we also create a ViewBag like citybag and store country name in this bag and finally we bind them to DropdownList. Llok at this how it is possible :

   @Html.DropDownList("cnm", (IEnumerable<SelectListItem>)ViewBag.cityList,"Select Course")

In above line Define that “cnm” is the name of country and cityList contain the number of country that we are add in action Result Result Create Method.

you have to create a one table for country in Databasewith name k_country like




to show example of upload multiple file in MVC upload multiple file in database in mvc

Example of auto complete Textbox search Autocomplete Search in Ajax

To Download Complete example click below download image link

download here!
Create two Class in Model Folder course.cs and class1.cs

Course.cs:-



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

namespace StudentRecord.Models
{
    public class Course
    {

        public int cid { get; set; }

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



class1.cs:-



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

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;

namespace StudentRecord.Models
{
    public class Class1
    {
        private static string Config = "Data Source=SQLDB;User ID=Demoh;Password=Demo1@";

        public List<Course> DropCourse()
        {
            SqlConnection db = new SqlConnection(Config);
          //  Database db = new SqlDatabase(Config);
            string query = "select cid,cnm from k_country";
            SqlCommand cmd = new SqlCommand(query,db);
            db.Open();
          //  SqlDataReader sr = cmd.ExecuteReader();
         
            List<Course> list = new List<Course>();
            using (IDataReader dataReader = cmd.ExecuteReader())
            {
                while (dataReader.Read())
                {
                    Course obj = new Course();
                    if (dataReader["cid"] != DBNull.Value)
                    {
                        if (dataReader["cid"] != DBNull.Value) { obj.cid = (int)dataReader["cid"]; }
                        if (dataReader["cnm"] != DBNull.Value) { obj.cnm = (string)dataReader["cnm"]; }
                        list.Add(obj);
                    }
                }
                return list;
            }
        }
    }
}


drpdwn controller:-



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

namespace StudentRecord.Models
{
    public class drpdwnController : Controller
    {
        //
        // GET: /drpdwn/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Create()
        {
            Class1 dbconnection = new Class1();
            List<Course> pcontent = new List<Course>();
            {
                //Get all page content from TblHome table
                pcontent = dbconnection.DropCourse();

            };
            List<SelectListItem> cityList = new List<SelectListItem>();
            //List<string> items = new List<string>();
            foreach (var item in pcontent)
            {
                cityList.Add(new SelectListItem
                {
                    Text = item.cnm,
                    Value = item.cid.ToString()
                });
            }

            ViewBag.CityList = cityList;
            return View();


            //return View(pcontent);
        }
        //
        // GET: /drpdwn/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /drpdwn/Create

    
        //
        // POST: /drpdwn/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /drpdwn/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /drpdwn/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /drpdwn/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /drpdwn/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}


Create.cshtml:-



@model StudentRecord.Models.Course

@{
    ViewBag.Title = "create";
}

<h2>create</h2>



       <fieldset>
    <legend>Course</legend>

    <div class="display-label">CourseName</div>
    <div class="display-field">
       @Html.DropDownList("cnm", (IEnumerable<SelectListItem>)ViewBag.cityList,"Select Course")
     @* @Html.DropDownList("employeeDetailsDiv");*@
    </div>
    </fieldset>
 @using (Html.BeginForm())

{
<p>
   <input type="Submit" value="Submit" />

    </p>

  
}

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

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")
}



Layout.cshtml:-

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title - My ASP.NET MVC Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <header>
            <div class="content-wrapper">
                <div class="float-left">
                    <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
                </div>
                <div class="float-right">
                    <section id="login">
                        @Html.Partial("_LoginPartial")
                    </section>
                    <nav>
                        <ul id="menu">
                            <li>@Html.ActionLink("Home", "Index", "Home")</li>
                            <li>@Html.ActionLink("About", "About", "Home")</li>
                            <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                             <li>@Html.ActionLink("Create", "Create", "drpdwn")</li>
                        </ul>
                    </nav>
                </div>
            </div>
        </header>
        <div id="body">
            @RenderSection("featured", required: false)
            <section class="content-wrapper main-content clear-fix">
                @RenderBody()
            </section>
        </div>
        <footer>
            <div class="content-wrapper">
                <div class="float-left">
                    <p>&copy; @DateTime.Now.Year - My ASP.NET MVC Application</p>
                </div>
            </div>
        </footer>

        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)
    </body>
</html>


This entry was posted in :

8 comments: