Using "ViewData" in ASP.NET MVC

by Jagadish Pulakhandam on 6/13/2012 6:58:08 PM
Rated 0 from 0 votes
Brief: Demonstrates on using "ViewData" between View and Controller in an ASP.NET MVC application.
Posted to: Basic Tutorials/samples on ASP.NET MVC Programming
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Attached sample demonstrates the following:
  • Using "ViewData" in Controller (in ASP.NET MVC)
  • Using "ViewData" in View (in ASP.NET MVC)
  • Sharing data/information between View and Controller using "ViewData" (in ASP.NET MVC).

Screen shot:



Source Code:

Model:

01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Web;
05. 
06.namespace MvcApplication1.Models
07.{
08.    public class SimpleMathInput
09.    {
10.        public int? FirstNo { get; set; }
11.        public int? SecondNo { get; set; }
12.    }
13.}

Controller:

01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Web;
05.using System.Web.Mvc;
06.using MvcApplication1.Models;
07. 
08.namespace MvcApplication1.Controllers
09.{
10.    public class SimpleMathController : Controller
11.    {
12.        //
13.        // GET: /SimpleMath/
14. 
15.        [AcceptVerbs(HttpVerbs.Get)]
16.        public ActionResult Index()
17.        {
18.            return View();
19.        }
20. 
21. 
22.        [AcceptVerbs(HttpVerbs.Post)]
23.        public ActionResult Index(SimpleMathInput o)
24.        {
25.            string result = string.Empty;
26. 
27.            if (o.FirstNo.HasValue && o.SecondNo.HasValue)
28.            {
29.                result = string.Format("Sum = {0}", o.FirstNo.Value + o.SecondNo.Value);
30.            }
31. 
32.            ViewData["result"] = result;
33. 
34.            return View(o);
35.        }
36. 
37. 
38.    }
39.}

View:

01.<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.SimpleMathInput>" %>
02. 
03.<!DOCTYPE html>
04.<html>
05.<head runat="server">
06.    <title>Index</title>
07.</head>
08.<body>
09.    <div>
10.        <%using (Html.BeginForm())
11.          { %>
12.        Enter First No:
13.        <%=Html.TextBox("FirstNo") %><br />
14.        Enter Second No:
15.        <%=Html.TextBox("SecondNo") %><br />
16.        <input type="submit" />
17.        <br />
18.        <%= ViewData["result"] %>
19.        <%} %>
20.    </div>
21.</body>
22.</html>


Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following