Viewing controller data in VIEW - asp.net-mvc

i'm newbie to MVC 3.0 and LINQ to SQL. called store procedure and saved it result in VAR but now how to view it's data in VIEW ?
CODE:
using EmployeeAttendance_app.Models;
namespace EmployeeAttendance_app.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Employee Attendance";
var DataContext = new EmployeeAtdDataContext();
var EmployeeAtd = DataContext.GetAttendance_Sp;
return View(EmployeeAtd);
}
public ActionResult About()
{
return View();
}
}
}
SP:
Select * from V_EmpAtd
View:
#foreach (GetAttendance_SpResult emp in (IEnumerable<Object>)ViewData.Model)
{
<li>#emp.DeptName</li>
}
this view shows the results, successfully :) but i don't understand that why do i need "GetAttendance_SpResult" in foreach and how
return View(EmployeeAtd);
in controller is related to this ?

right click within your action and select 'Create View'
public ActionResult Index()
{ // right click here...
then visit the view /HomeController

Where is your model? "M" "V" "C" ;-)
First you should create a class (your model, called for example EmployeeModel- you should take a name corresponding to the type of your data) corresponding to the fields of your items of your database results. How? Look here:
http://www.asp.net/mvc/tutorials/mvc-5/introduction/adding-a-model
The list of items corresponding to that model will be passed to your View in your controller so your view should start with:
#model IEnumerable<yourNameSpace.Models.EmployeeModel>
And then in your view you will be able to display the properties of your item. Sample for a table:
<table>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.DeptName)
</td>
</tr>
}
</table>
But you can do what you want: a list, ...
In a few words: back to MVC basics. See sample here: http://www.asp.net/mvc/tutorials/mvc-5/introduction/accessing-your-models-data-from-a-controller, especially when they are in "Examining the Generated Code".

Related

Passing data base info from controller to view in .NET MVC

Hello I'm trying to pass some database info from my controller to my view, but don't find the best way to do it. I'm populating the model in my controller, but I need to populate those values from database. I have a class called DataAccess which is the one that contains all my queries but not sure where I should put the logic to populate. I would say a for loop in my controller to populate the values, but seems to fail since I'm declaring the SchedulerViewModel there
The idea is having my values next to a radio button, so when selecting a radio button, I can "detect" the value and do something with that option....any suggestion would be appreciated...
My model:
public class SchedulerViewModel
{
public string theValue { get; set; }
public SelectListItem[] Items { get; set; }
}
My Controller:
public ActionResult Scheduler()
{
//DataAccess dataAccess = new DataAccess();
//for loop here???
var model = new SchedulerViewModel
{
Items = new[]
{
new SelectListItem { Value = "U", Text = "USA" }
}
};
return View(model);
}
My view:
#using (Html.BeginForm())
{
for (int i = 0; i < Model.Items.Count(); i++)
{
#Html.RadioButtonFor(x => x. theValue, Model.Items[i].Value, new { id = "item_" + i })
#Html.Label("item_" + i, Model.Items[i].Text)
<br />
}
}
Ideally you would have a service class that handles your database access. You shouldn't directly invoke the data layer from the controller, although nothing prevents you from doing it. For simplicity, I'm just putting calling the data access directly in the controller. The idea is that you need to return a collection of data, here an IEnumerable, in the View at the controller level so that the View can display this data.
Controller:
[HttpGet]
public ActionResult Index()
{
KnowledgeBaseEntities context = new KnowledgeBaseEntities();
IEnumerable<ISSUE> issues = context.ISSUES;
if(issues == null)
{
return HttpNotFound();
}
return View(issues);
}
View:
As you can see I'm referencing the collection of data that I'm expecting from the controller.
#model IEnumerable<ISSUE>
In this case it's an IEnumerable just like I had in the controller. Then you'll notice I'm referencing a Model object when I iterate the model.
#foreach (var item in Model)
Then I'm looping through each row of the model in order to add table rows to the table. Because we're using Model Binding from the Entity Framework. We're using Razor Syntax. You also notice I'm using Action Links for each row in the last column. This allows me to Edit, Delete or provide Details for a row of data. However, I will need to invoke another Controller Action for that. For example, you'd have an Edit controller action method that returns a single ISSUE to an Edit View.
#model IEnumerable<ISSUE>
#{
ViewBag.Title = "Knowledge Base Issues";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 class="line">All Issues</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="flat">
<tr>
<th>#Html.DisplayNameFor(model => model.KEYWORDS)</th>
<th>#Html.DisplayNameFor(model => model.SUBJECT)</th>
<th>#Html.DisplayNameFor(model => model.DATE_ENTERED)</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(modelItem => item.KEYWORDS)</td>
<td>#Html.DisplayFor(modelItem => item.SUBJECT)</td>
<td>#Html.DisplayFor(modelItem => item.DATE_ENTERED)</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ISSUE_ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ISSUE_ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ISSUE_ID })
</td>
</tr>
}

Insert new rows into existing table on view

This is my table in the view (cshtml) :
<table id="tblketquatk" class="thongke2socuoi">
<tbody>
<tr>
<th>Số</th>
<th>Ngày về gần nhất</th>
<th>Số lần xuất hiện</th>
<th>Số ngày chưa về</th>
</tr>
</tbody>
</table>
In the controller :
[HttpPost]//Run action method on form submission
public ActionResult LastTwoSubmit(string cityID, string numbers, int days, bool onlySpecial)
{
// get the result from sql server based on the parameters
// now i want to append the result to the table tblketquatk
return View();
}
Now I want to append the result to the table tblketquatk, is there anyway to do this without using Javascript?
I've done this before using JQuery, which will use Ajax to append the result into the exisiting table without reloading the page.
Link to JsFiddle for a better look.
What I want is how to insert the newly returned dataset into the table, and the parameters on the form remain unchanged/reset.
Any help is greatly appreciated!
You need models to bind to so that model can be returned to the view
public class SearchViewModel
{
public int Days { get; set; }
....
}
public class MainViewModel
{
public SearchViewModel Search { get; set; }
// Add a property for the collection of items you are rendering in the table
}
View
#model MainViewModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.Search.Days)
....
<input type="submit" ... />
}
// add loop to create table rows
Controller
[HttpPost]
public ActionResult LastTwoSubmit(MainViewModel model)
{
// use the values of model.Search to query the database and add to the model collection
return View(model);
}
because you form properties are now bound to a model and your returning that model, the values will be retained when you return the view.

Database from controller to view

Well, I have done this code before and it has worked, but this time it just wont work, please help me out here. I have searched the web for hours and tested many options, can't make it work. As you might have guessed I just want everything from my database (written in ssms) to be passed to the view, without errors. I get many different errors, the latest error is:
The model item passed into the dictionary is of type System.Collections.Generic.List1[System.String]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[FE.Blog]'.
The controller:
public ActionResult Contact()
{
var q = from p in dbBlog.Blog
select p.Description;
return View(q.ToList());
}
The View:
#model IEnumerable<FE.Blog>
#foreach (var item in Model)
{
#item.Description
}
You are selecting just one column p.Description which is string but your view expects Model to be IEnumerable<FE.Blog>.
So change your model in view if you need only on column:
#model List<string>
#foreach (var item in Model)
{
#item
}
Or if you want the view to bind with IEnumerable<FE.Blog> then you have to the object in query instead of just selecting one property:
public ActionResult Contact()
{
var q = from p in dbBlog.Blog
select p;
return View(q.ToList());
}
and in View:
#model IEnumerable<FE.Blog>
#foreach (var item in Model)
{
#item.Description
}
I just solved my problem I think, it looks so.
The problem was that I had forgot the "#model FE.Blog" above another forms using-statement in another View. There are partials view all over the place, this explains the errors I've been collecting.
Regards

How to list the records from different tables inside cshtml view?

I am having a problem in a ASP.NET MVC project. I have a database where I have several tables, and I want to list all the records inside each table in my View, I am able to do this using only one table, I am going to provide here the code that works with one table and what I am trying to do.
Controller:
Using only one table I would do:
Mp5DataclassesDataContext db = new Mp5DataclassesDataContext();
public ActionResult Admin()
{
return View(db);
}
This is what I am trying to do:
return View(db);
At this point I can debug and see that all my tables are in that db object, with all the correct data. Then the problem is in my View
View:
#*This is defined at the top of my .cshtml*#
#model IEnumerable<Interface_AutoUtad.Models.Mp5DataclassesDataContext>
#*This is the code that works with only one table*#
#foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item.table_column)
}
#*What I am trying to do:*#
#foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item.some_other_table.table_column)
}
I can't get this last part to work because "some_other_table" doesn't show up.
Is there a way I can achieve this ? I want to Iterate through each table and inside iterate through each record in that table.
Thank you all in advance :)
It looks like you've set the "model" for your view to be your application's DbContext. Don't do that. Views are only processed at runtime, and querying into your database is way too much logic for a view. Any errors will only be exposed at runtime, and you have a huge potential for errors.
Views are designed to work with only one type. If you need to work with multiple types in the same view, you can either utilize a view model or use child actions.
View Model
public class MultipleTypesViewModel()
{
public IEnumerable<SomeType> SomeTypes { get; set; }
public IEnumerable<OtherType> OtherTypes { get; set; }
...
}
Then in your view:
#model Namespace.To.MultipleTypesViewModel
...
#foreach (var item in Model.SomeTypes)
{
#Html.DisplayFor(modelItem => item.table_column)
}
#foreach (var item in Model.OtherTypes)
{
#Html.DisplayFor(modelItem => item.table_column)
}
...
Child Actions
[ChildActionOnly]
public ActionResult ListSomeTypes()
{
var someTypes = db.SomeTypes.ToList();
return PartialView(someTypes);
}
[ChildActionOnly]
public ActionResult ListOtherTypes()
{
var otherTypes = db.OtherTypes.ToList();
return PartialView(otherTypes);
}
...
Then, create an appropriate partial view for each:
ListSomeTypes.cshtml
#model IEnumerable<Namespace.To.SomeType>
#foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item.table_column)
}
ListOtherTypes.cshtml
#model IEnumerable<Namespace.To.OtherType>
#foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item.table_column)
}
Etc. And then finally in your main view:
#Html.Action("ListSomeTypes")
#Html.Action("ListOtherTypes")
(In this case, the model of the main view is totally irrelevant.)

How to pass List from Controller to View in MVC 3

I have a List<> binded with some data in Controller action and I want to pass that List<> to View to bind with DataGrid in Razor View.
I am new to MVC.Can any one help me how to pass and how to access in View.
Passing data to view is simple as passing object to method. Take a look at
Controller.View Method
protected internal ViewResult View(
Object model
)
Something like this
//controller
List<MyObject> list = new List<MyObject>();
return View(list);
//view
#model List<MyObject>
// and property Model is type of List<MyObject>
#foreach(var item in Model)
{
<span>#item.Name</span>
}
I did this;
In controller:
public ActionResult Index()
{
var invoices = db.Invoices;
var categories = db.Categories.ToList();
ViewData["MyData"] = categories; // Send this list to the view
return View(invoices.ToList());
}
In view:
#model IEnumerable<abc.Models.Invoice>
#{
ViewBag.Title = "Invoices";
}
#{
var categories = (List<Category>) ViewData["MyData"]; // Cast the list
}
#foreach (var c in #categories) // Print the list
{
#Html.Label(c.Name);
}
<table>
...
#foreach (var item in Model)
{
...
}
</table>
Hope it helps
You can use the dynamic object ViewBag to pass data from Controllers to Views.
Add the following to your controller:
ViewBag.MyList = myList;
Then you can acces it from your view:
#ViewBag.MyList
// e.g.
#foreach (var item in ViewBag.MyList) { ... }
Create a model which contains your list and other things you need for the view.
For example:
public class MyModel
{
public List<string> _MyList { get; set; }
}
From the action method put your desired list to the Model, _MyList property, like:
public ActionResult ArticleList(MyModel model)
{
model._MyList = new List<string>{"item1","item2","item3"};
return PartialView(#"~/Views/Home/MyView.cshtml", model);
}
In your view access the model as follows
#model MyModel
foreach (var item in Model)
{
<div>#item</div>
}
I think it will help for start.

Resources