Tuesday, 21 January 2014

ViewData and ViewBag in MVC 4


 Both ViewData and ViewBag are used to pass the data from controller to view. ViewData is a dictionary of objects that are stored and retrieved using strings as keys.
ViewData[“counties”]=”list of countries”;  ViewBag.countries=”list of countries”;
ViewBag uses the  dynamic feature that was introduced into C# 4.It allows an object to have properties dynamically added to it.

Both ViewData and ViewBag does not provide compile time error checking. For example  ,if you mis-spell keys or property names, you wouldn’t get compile time error. You get to know about the error at runtime only. Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary
To pass the data from controller to a view, It’s always good practice to use strongly typed view models over ViewBag and ViewData. Strongly typed View Models provide compile time error checking.

tags:viewdata in mvc 4,viewbag in mvc4 ,viewdata and viewbag ,viewbag ,viewdata in mvc,viewbag in mvc

Views in MVC 4 Application

In This article I am going to explain views in mvc application.I want to display list of countries as shown in figure.


  Now go to visual studio create one empty mvc cotroller or we can use home controller and look at the index action method return type is ActionResult but we want to display the list of countries means we have to return the list of strings.
public List<string> Index()
        {
            return new List<string>()
            {
                "India",
                "France",
                "USA",
                "Canada",
                "England"
            };
        }

Run the application, give the controller name in url and we expect the output as list of countries but we will get name of the type (System.Collections.Generic.List`1[System.String])



To fix this we can actually add a view .The purpose of view is to format the data in page we want and present it to the end user. First we need to add a view to the project, right click any where on the index function and select add view.





The name of view and the name of the controller action method matching here, select razor as view engine and leave the rest of defaults we discuss strongly typed view in coming articles. Before going to click on add just watch the views folder ,it has no files now add a view watch the views folder it has index.cshtml file.
To return a view first we have to change return type of index action method. I will change return type as ActionResult, view inherits from ActionResult. We have to pass the list of counties from controller to view,to achieve this we need to store these list of counties in ViewBag or ViewData. ViewBag and  ViewData is a mechanism to pass data from controller to view.

Here Counties (viewbag.countries) is dynamic property, you can give any meaningful name instead of countries.
Now go to view i.e Index.cshtml ,In this view we need to retrieve the list of countries from the viewbag object and display them to the user. Let’s change the code in the Index.cshtml

In above code we use @ symbol to switch between html and c# code. Now run the application and see the following output

tags:views in mvc  ,views in asp.net mvc ,views in mvc 4,
views in mvc 4

Friday, 6 December 2013

Genarating Radiobuttonlist Control in MVC 4

Here i am going to explain generate a radiobuttonlist in mvc. In previous articles i am explained code first approach,before seeing this article please see that article,you will get better idea on how to enable migrations,and how to craete data context class.click here to go that article. For this Create Two Model Classes one is Department and another one is Company.

 public class Department
    {
        [Key]
        public int DeptId { get; set; }
        public string DeptName { get; set; }
    }


Create company Model class and write the following code

public class Company
    {
        public string SelectDepartment { get; set; }

        public List<Department> departments
        {
            get
            {
                DataContext db = new DataContext();
                return db.department.ToList();
            }
        }

    }


In above code DataContext class is in Models folder..(to know about datacontext class and furthur details click here)

datacontext class
public class DataContext:DbContext
    {
        public DataContext() : base("EmployeeDb")
        {
        }
        public DbSet<Employee> employee { get; set; }

        public DbSet<Department> department { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

            base.OnModelCreating(modelBuilder);
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, Configuration>());
            modelBuilder.Entity<Employee>().ToTable("employee");
            modelBuilder.Entity<Department>().ToTable("department");
     }

 we have to include department class in datacontext class..if we change model class the database table will be changed for that we have to write onmodelcreating method.




Now go to Home controller and write one action method name it as Radio and write the following code

 public ActionResult Radio()
        {
            Company comapny = new Company();
            return View(comapny);
        }


right click on radio and add view to action method



now write radiobutton control in form and write the following code

@model MvcEmployee.Models.Company

@{
    ViewBag.Title = "Radio";
}

<h2>Radio</h2>
@using (Html.BeginForm())
{
    foreach(var dept in Model.departments)
    {
       @Html.RadioButtonFor(m=>m.SelectDepartment,dept.DeptId)@dept.DeptName
  

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







Now go to Home Controller write the HttpPost method for Radio Action method

  [HttpPost]
        public string  Radio(Company company)
        {
            if (string.IsNullOrEmpty(company.SelectDepartment))
            {
                return "You did not select any department";
            }
            else
                return "You selected department with Id " + company.SelectDepartment;

        }






Now run the application and you see the following output









 If you didn't select any department and click on submit it shows "You did not select any department".
If you select Finance department and click on submit  it shows "You selected department with Id 3"


tags:radiobuttonlist in mvc 3,radiobuttonlist in mvc ,radiobuttonlist in mvc 4,radiobuttonlist in mvc 5,generate radiobuttonlist in mvc,radiobuttonlist and getting the values from data base,how to create radiobutton in mvc 4 razor,radiobutton in mvc razor,radiobutton list asp.net mvc 4

Thursday, 5 December 2013

DropDownList in MVC 4


Here I am going to explain the generating drop downl ist and get the values from database table. First of all create one Model class named as Department. This example is explained in code first approach .For this follow the below procedure .In previous articles i am explained code first approach,before seeing this article please see that article,you will get better idea on how to enable migrations,and how to craete data context class.click here to go that article.
To open vs 2010 and to create new project and for code first approach click here

 Directly i am going to Model's folder and add department Model class




public class Department
    {   [Key]
        public int Id { get; set; }
        public string Name { get; set;}
    }















 Change the DataContext class(how to create datacontext clas click here)

include the department model class in datacontext class

 add namespace using MvcEmployee.Migrations;
public class DataContext:DbContext
    {
        public DataContext() : base("EmployeeDb")
        {
        }
        public DbSet<Employee> employee { get; set; }

        public DbSet<Department> department { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

            base.OnModelCreating(modelBuilder);
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, Configuration>());
            modelBuilder.Entity<Employee>().ToTable("employee");
            modelBuilder.Entity<Department>().ToTable("department");
     }

    }






 Now go to Home Controller and write action method name it as Dept and write the following code.

create the instance for DataContext class

Add namespace using MvcEmployee.Models;

private DataContext db = new DataContext();

public ActionResult Dept()
        {
            ViewBag.Departments = new SelectList(db.department, "DeptId", "DeptName");
            return View();
        }

Add view to Dept Action method and write the following in Dept.cshtml

 @Html.DropDownList("Departments", "Select Department")



The Departments should be same as Viewbag attribute name in home controller


Now run the application and you see the following output
 There is no records in the Dropdownlist.Now go to database insert few records in department table.(If the table has records ,those are loaded into dropdownlist.)

Now run the application see the following output


tags:dropdownlist in mvc ,dropdownlist in mvc 3,dropdownlist in mvc 4,dropdownlist in mvc razor,dropdownlist in mvc get the values from database,dropdownlist in asp.net mvc, dropdownlist in asp.net mvc 5,generate dropdownlist in asp.net mvc,how to create dropdownlist in mvc 4,how to create dropdownlist in mvc5