I am proud to write the first article in MVC. I am brand new to MVC at this date. I saw the ways to convey the message between the control to the view, the easiest ways are viewbag and viewdata both are nearly do the same in the difference way.
ex:
in the view
<body>
<h1><%=ViewBag.Greeting%></h1>
<h2.<%=ViewData["Greeting"]%></h1>
</body>
1. The simple difference is we use a string in the ViewData for indexing purpose that is called magic string but in the ViewBag method view simply use the property similar to the class.
2. For the both cases the intelligence is not provided. So there may be chances to make a manual mistake to indicating the variables.
* If you made mistake in the ViewData ex ViewData["Greting"] instead of Greeting at the time the error is ignored and HTML is executed without any error.
* But it is strictly notified in the ViewBag method.
3. In the ViewBag the data conversion is handled by itself no need to convert the data from object to the data type. But it must be defined in the ViewData.
ex:
List<string> namelist = new List<string>{"sugunthan","shamnugam","sundaram"};
ViewBag.list = namelist;
ViewData["list"] = namelist;
return View();
}
In the View
<ul>
<%foreach (var name in (List<int>) ViewData["list"]){ %>
<li><%=name %></li>
<%} %>
</ul>
<ul>
<%foreach (var name in ViewBag.list)
{ %>
<li> <%=name %></li>
<% }%>
</ul>
If you made any mistake in the data conversion it make an error in the runtime.
ex:
public ActionResult Index()
{
{
ViewBag.Greeting="Hello World";
ViewData["Greeting"]="Hello World";
}
in the view
<body>
<h1><%=ViewBag.Greeting%></h1>
<h2.<%=ViewData["Greeting"]%></h1>
</body>
1. The simple difference is we use a string in the ViewData for indexing purpose that is called magic string but in the ViewBag method view simply use the property similar to the class.
2. For the both cases the intelligence is not provided. So there may be chances to make a manual mistake to indicating the variables.
* If you made mistake in the ViewData ex ViewData["Greting"] instead of Greeting at the time the error is ignored and HTML is executed without any error.
* But it is strictly notified in the ViewBag method.
3. In the ViewBag the data conversion is handled by itself no need to convert the data from object to the data type. But it must be defined in the ViewData.
ex:
public ActionResult Index()
{List<string> namelist = new List<string>{"sugunthan","shamnugam","sundaram"};
ViewBag.list = namelist;
ViewData["list"] = namelist;
return View();
}
In the View
<ul>
<%foreach (var name in (List<int>) ViewData["list"]){ %>
<li><%=name %></li>
<%} %>
</ul>
<ul>
<%foreach (var name in ViewBag.list)
{ %>
<li> <%=name %></li>
<% }%>
</ul>
If you made any mistake in the data conversion it make an error in the runtime.
No comments:
Post a Comment