Differences between viewdata, viewbag and tempdata in mvc3


Differences between viewdata, viewbag and tempdata in mvc3

 

In Asp.net MVC, we have three objects – ViewData, ViewBag and TempData to pass data from controller to view and in next request.

ViewData

1.ViewData is a dictionary object that is derived from ViewDataDictionary class.

2.ViewData is used to pass data from controller to corresponding view.

3.It’s life lies only during the current request.

4.If redirection occurs then it’s value becomes null.

5.It’s required typecasting for complex data type and check for null values to avoid error.

ViewBag

1.ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.

2.Basically it is a wrapper around the ViewData and also used to pass data from controller to      corresponding view.

3.It’s life also lies only during the current request.

4.If redirection occurs then it’s value becomes null.

5.It doesn’t required typecasting for complex data type.

TempData

1.TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.

2.TempData is used to pass data from current request to subsequent request means incase of redirection.

3.It’s life is very short and lies only till the target view is fully loaded.

4.It’s required typecasting for complex data type and check for null values to avoid error.

5.It is used to store only one time messages like error messages, validation messages.

ViewData, ViewBag and TempData Current Request Example

public class HomeController : Controller
{
public ActionResult Index()
{
var cust= new Customer
{
CustID=101,
Name = "Rajesh",

};
ViewData["cust"] = cust;
ViewBag.Customer = cust;
TempData["cust"] = cust;
return View();
}
}

return View(); }
}
@model MvcSample.Models.CustomerModel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Welcome to MVC Tutorails";
var viewDataCustomer = ViewData["cust"] as Customer; //need typcasting
var tempDataCustomer = TempData["cust"] as Customer; //need typcasting
}
<h2>Welcome to MVC Tutorials</h2>
This Best behavioral customer is!
<h4>@ViewBag.cust.Name</h4>
<h3>@viewDataCustomer.Name</h3>
<h2>@tempDataCustomer.Name</h2>
</div>

ViewData, ViewBag and TempData Next Request Example

public ActionResult About()
{
var cust= new Customer {
CustID=007,
Name = "Rajesh",
};
ViewData["cust"] = cust;
ViewBag.Customer = cust;
TempData["cust"] = cust;
//After the redirection, ViewData and ViewBag objects will be null
//Only TempData will exist after redirection
return View();
}
@model MvcSample.Models.Customermodel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Detail";
var tempDataCustomer = TempData["cust"] as Customer; //need typcasting
}

Advertisements

How To Get CheckBox Selected Values in Controller In MVC3


Introduction

In this article i am going to define u you how we can get selected values of checkbox in mvc3 in controller.in this article u will also get to know about multiple form in a single view how to use them.

Step 1: Make a new Empty Project using mvc3 in visual studio 2010.

Step 2: Now Add Collection Class in Model folder by Right click on model whose code would be such as below given.

 public class MyViewModel
    {
        public int Id { get; set; }
        public bool Checkbox { get; set; }
        public string Value { get; set; }
    }
 
 
    // view model for checklistbox
    public class CheckBoxListViewModel
    {
        public List<CheckListBoxItem> Items { get; set; }
 
        // the name of this list should be the same as of the CheckBoxes otherwise you will not get any result after post
        public List<string> SelectedValues { get; set; }
    }
 
    // represents single check box item
    public class CheckListBoxItem
    {
        public string Value { get; set; }
        public string Text { get; set; }
        public bool IsCheck { get; set; }
    }

Step 3: After this add a HomeController in Controller Folder and write in that below given code.

public ActionResult Index()
        { 
 
            var list = new List<MyViewModel>
            {
                new MyViewModel { Id = 1, Checkbox = false ,Value="Coal"},
                new MyViewModel { Id = 2, Checkbox= false ,Value="Cotton"},
                new MyViewModel { Id = 3, Checkbox = false ,Value = "Fabric"},
            };
            var outObj = list.Select(row => new SelectListItem()
                            {
                                Text = row.Value,
                                Value = row.Id.ToString(CultureInfo.InvariantCulture),
                                Selected = row.Checkbox
                            });
            ViewBag.keydata = outObj;
            // pass ViewModel object to View for display
 
            return View();
        }

Step 4 :  Now Add your view index.cshtml in view folder and paste in his below given code.

@{
    ViewBag.Title = "Index";
    var obj = ViewBag.keydata;
}
@using (Html.BeginForm("Index", "Home"))
{
    IEnumerable<SelectListItem> ct = ViewBag.keydata;
    foreach (var item in ct)
    {
    @Html.CheckBox("chk", item.Selected, new { value = item.Value });<label>@item.Text</label>
    }
<div>
       <input type="submit" value="Send" name="action:Send" /></div>
}

Step 5:  Now Make your Index Action with HttpPost Attribute in Controller which is below given.

 [HttpPost]
        [MultipleButton(Name = "action", Argument = "Send")]
        public ActionResult Index(FormCollection obj)
        {
           
            if (obj != null)
            {
                string[] AllStrings = obj["chk"].Split(',');
                foreach (string item in AllStrings)
                {
                    if (item.Contains("false"))
                    {
 
                    }
                    else
                    {
                        var outk = item;
                    }
 
 
 
                    // handle value
                }
            }
           
            return RedirectToAction("Index", "Home");
        }
Now Run by pressing f5 and See by putting Result in Your action you will get your all selected
Check boxes values.

If you Want to Download complete source of this article you can get to download it by click on below given url

https://docs.google.com/file/d/0B-sDsBkcsM1YWV9PWVUwYlVHRjA/edit?usp=sharing