Click here to Skip to main content
15,904,339 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi All,

I am just getting into learning MVC .Net framework. So this might be a very basic question.In my project i am using Entity Framework and i have connect this project to a server containing the database I want to be queering from.

After connecting to a database using ADO.Net, Visual Studio generated a model class for like so ...


C#
public int Id {get; set;}
   public string Name {get;set;}
   public string College {get;set;}




Now In my controller i am using a viewBag in order to pass data to the view. I followed tutorial that showed how to pass data to view using a viewBag.. basically like so..

C#
ViewBag.Name = "Steve"

and then in the view you type something like so:
HTML
name: @ViewBag.Name



Now back to my project, how do i query from database using a viewBag?


As you can see I have model that has already been generated for me, i am just stuck on how to get this data into a Viewbag and then pass it on to a view.

Thank you in advance
Posted

1 solution

The way you assigned a variable called Name, similarly you assigned an object into ViewBag.


Say the class is

C#
class Student 
{
   public int Id {get; set;}
   public string Name {get;set;}
   public string College {get;set;}
}


you create/get an object for this class.

C#
Student objStudent  = new Student();
ViewBag.Student = objStudent;


In your .cshtml file,

Razor
@{
var Student = ViewBag.Student;
<input type="text" value="@Student.Name">
}


I suggest to have strongly typed view instead of using ViewBag.

http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/strongly-typed-views-in-mvc/[^]




http://www.c-sharpcorner.com/UploadFile/db2972/strongly-typed-view-list-sample-in-mvc-day-24/[^]



http://www.asp.net/mvc/overview/views/dynamic-v-strongly-typed-views[^]</input>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900