Listing Models from ASP pages, with Visual Studio and C# - c#

I am creating a very basic Web application in ASP with Visual Studio, I used the default web site then created the 'Employee' Model. This Model can be stored in the Database using:
public class EmployeeDBContext : DbContext
{
public DbSet<Employee> Employees{ get; set; }
}
In the Employee namespace. When I created the Controller for this Model the default Create, Read, Update and Delete methods are created. There is also an index page created that is shown when the page is 1st loaded and this page shows every Employee currently in the database. The code for Index.cshtml looks like this:
#model IEnumerable<AnotherWebApp.Models.Employee>
#{
ViewBag.Title = "Index";
}
<h2>All Employee Options</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<p>
#Html.ActionLink("View All", "ViewAll")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Role)
</th>
<th>
<b>Options</b>
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Role)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
What I am trying to do is display a basic menu on Index.cshtml and link to a ViewAll page containing the table of all Employees. The problem is it says 'Object reference not set to an instance of an object.' and the page is not displayed. I cannot see why this code works on Index.cshtml but will not work on ViewAll.cshtml, anybody have suggestions?? Here is a link to some tutorials doing this: http://www.asp.net/mvc/tutorials/mvc-5/introduction/accessing-your-models-data-from-a-controller
Thanks for any advice.

Just to clear things up this problem was from the EmployeeController.cs where the View associated with the ViewAll page was being returned. When the ViewAll function looked like this:
public ActionResult ViewAll()
{
return View();
}
The list of Employees could not be accessed so
#model IEnumerable<AnotherWebApp.Models.Employee>
was null.The correct version of this function is:
public ActionResult ViewAll()
{
return View(db.Employees.ToList());
}
Now the list of all Employees is accessible and can be easily displayed on the ViewAll page.
Hope this is of help to somebody, if anybody has furthur questions please ask!!

Related

How do I get my view to recognize my object

I already have a view created that I want to use to display results being pulled from the db and passed to the view in my action. When I created the view I didn't tell it what objects I wanted to pass in so I'm trying to add them manually but the view doesn't seem to recognize them.
Here is my Results view and the top line is what I'm trying to add, but VS doesn't recognize it. So spaces is red (unrecognized) and item.Name and item.description are red
#spaces IQueryable<GiftExchange.Core.Models.Space.YogaSpace>
#{
ViewBag.Title = "Results";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>Search Results</h3>
#using (Html.BeginForm("Results", "Home", FormMethod.Get))
{
<p>
#Html.TextBox("Location") <input value='Search' type="submit" />
</p>
}
<table border="1">
<tr>
<th>
#Html.DisplayNameFor(spaces => spaces.Name)
</th>
<th>
#Html.DisplayNameFor(spaces => spaces.Description)
</th>
</tr>
#foreach (var item in spaces)
{
<tr>
<th>
#Html.DisplayFor(modelItem => item.Name)
</th>
<th>
#Html.DisplayFor(modelItem => item.Description)
</th>
</tr>
}
</table>
Here is my action
[AllowAnonymous]
public ActionResult Results(string searchTerm)
{
IQueryable<YogaSpace> spaces;
using (var repo = new YogaSpaceRepository())
{
spaces = repo.All;
}
return View(spaces);
}
In the first line of your view, switch #spaces for #model.
And then where you want to use it, instead of spaces, use Model.
For more details, google for "strongly typed views".

ASP.NET MVC PartialView with List

I am at my first MVC project. I want to create a page with a header and in this header to be placed a partial view with category list.
This is what I did so far:
I created the master page (_Home.cshtml). Than in Shared folder I created a View (Category.cshtml). See my picture.
My Category.cshtml content:
#model IEnumerable<ArtSchool.Models.Category>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Visible)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Visible)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
My master page file:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>_Home</title>
</head>
<body>
<div>
#Html.Partial("ASCX/Header")
#Html.Partial("Category")
#RenderBody()
</div>
When I run the project I got the error:
I know that is a newbie question but it's my first MVC project.
Thanks!
Solution 1
If you want to use partial view you need to pass model to this helper this way
#Html.Partial("Category", CategoryModel)
before you pass this model you have to fill it with some data.
Solution 2
also you can use #Html.Action() Method with name of ActionResult method which will return partial view for you.
for example:
#Html.Action("GetCategories", "ControllerName")
public ActionResult GetCategories() {
// fill some data for your model here
return PartialView("Category", model);
}
If you want to interpret those partials as some static sections inside your HTML, then I would suggest you to call Html.Action() which returns your partials:
#Html.Action("GetPageHeader","Home")
#Html.Action("GetPageCategories","Home")
HomeController
[HttpGet]
public ActionResult GetPageHeader()
{
return PartialView(#"~/Views/Shared/_PageHeader.cshtml");
}
[HttpGet]
public ActionResult GetPageCategories()
{
var categories = databaseContext.GetAllCategories(); //Get your categs
return PartialView(#"~/Views/Shared/_Categories.cshtml",categories);
}

How to add a comment box below an item on an CSHTML webpage ASP .NET MVC 4

I am trying to create a website that is used for blogging. I have a database connected to it and currently I only have blog posts working. I have a view that shows all of the blog posts by using the "List" type which is done through Visual Studio. Basically, it prints out all of the database entries I want to make it so other users can comment on these posts and all of the comments will be in a lower subsection of the post. I am new to web development so I am not really sure if there is a preferred way to do this.
Here is my CSHTML File
#model IEnumerable<Blogger.Models.Article>
#{
ViewBag.Title = "ViewAllArticles";
}
<h2>View All Posted Blogs</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Author)
</th>
<th>
#Html.DisplayNameFor(model => model.Content)
</th>
<th>
#Html.DisplayNameFor(model => model.DatePosted)
</th>
<th>
#Html.DisplayNameFor(model => model.IsAcceptingComments)
</th>
<th>
#Html.DisplayNameFor(model => model.LastEdited)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Author)
</td>
<td>
#Html.DisplayFor(modelItem => item.Content)
</td>
<td>
#Html.DisplayFor(modelItem => item.DatePosted)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsAcceptingComments)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastEdited)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
Here is my model (C# Code):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Blogger.Models;
namespace Blogger.Controllers
{
public class ArticleController : Controller
{
private ArticleDBEntities1 _entities = new ArticleDBEntities1();
//
// GET: /Article/
public ActionResult Index()
{
return View(_entities.Articles.ToList());
}
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude ="Id")]Article ArticleToCreate)
{
try
{
// Insert Logic Here
_entities.Articles.Add(ArticleToCreate);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return RedirectToAction("Index");
}
}
//View All Posts from all Users
public ActionResult ViewAllArticles()
{
return View(_entities.Articles.ToList());
}
}
}
I hope this source code can help understand what I am trying explain. I am open to all suggestions.
I would suggest creating a new model to support comments. You can then add a list of comments to a post and create a many to many mapping between your models. You can then have a Web method that allows the addition of comments linked to the post in question.
I will try and get some example code for you tomorrow.
You can separate it by making it a partial view and handle separately. It will be better not to mix things together thus keeping components loose coupled.
You have two other options.
1. Use entirely client side mechanism for the UI and comments will be handled by a WebAPI backend.
2. A third party commenting system like Disqus.
Please mark as answer if it helped you.

Accessing a field from a differen't model's table in ASP.NET MVC

I have a page that displays a filtered table based on the user that is passed to the page. I also want to display the user's info a the top of the page, but this comes from a different table (from the Account model). Is there a way I can access fields from this table while working in my other controller/views?
Here is my code:
#{
ViewBag.Title = "User Profile";
}
#model IEnumerable<FTv2.Models.Trade>
#{
ViewBag.Title = "Active Trades";
ViewBag.ImgUrl = ViewBag.Name + ".png";
}
<h2>#ViewBag.User's Profile:</h2>
<p>
// This is where I would like to put the User info.
</p>
<h2>Active Trades:</h2>
<p>
</p>
<table>
<tr>
<th>
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th>
#Html.DisplayNameFor(model => model.User)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
if (item.User == ViewBag.User)
{
<tr>
<td>
#{ViewBag.ImgUrl = #item.Name + ".png";}
<img src="/Images/#ViewBag.ImgUrl" HEIGHT="66" WIDTH="50" >
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price) TE
</td>
<td>
#Html.DisplayFor(modelItem => item.User)
</td>
#{if (ViewBag.User == User.Identity.Name){
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
}}
</tr>
}
}
</table>
There are two options that I can think of:
Render an action method that returns the user details
#{
Html.RenderAction("UserDetails", new { UserID = ViewBag.UserID});
}
Create a new model that has the user details plus an IEnumerable of the trades and use this for your view.
I suppose that you wanna
make page model that will contain the User Info and IEnumerable<...>.
or pass User info into ViewBag
or call #Html.RenderAction()
I think that you need to keep in mind the chance of reuse of the view model class. If you see no way to reuse the model then use ViewBag to pass the info into a View. In the Controller's Action set the property ViewBag.UserInfo = userInfo; and in the view call: code#Html.Partial("_UserInfo", (UserInfo)ViewBag.UserInfo)code.
But more practical way is to call #Html.Action():
1. Make action UserController.UserInfo(int id).
2. Call from your view #Html.Action("UserInfo", "User", new {Id = ViewBag.UserId});
3. create partial view for the UserController.UserInfo action.

MVC 4 How to pass an object to partial view when list item is clicked?

This is a controller
public class ProductController : Controller
{
//
// GET: /Product/
public ActionResult Index(int id = 0)
{
return View(DALCategory.GetCategoryList());
}
public PartialViewResult productPartial(int id)
{
if (id > 0)
{
return PartialView("_productPartial", DALProduct.GetProductListByCateDetail(id));
}
else
{
return PartialView("_productPartial", DALProduct.GetProductList());
}
}
This is code in index view
#model IEnumerable<Model.Category>
<h2>Products</h2>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.name)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.ActionLink(#item.name, "productPartial", new { id = item.id })
</td>
</tr>
}
</table>
#Html.Partial(productPartial)
And this is code for partial view.
#model IEnumerable<Model.Product>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.SKU)
</th>
<th>
#Html.DisplayNameFor(model => model.product_name)
</th>
<th>
#Html.DisplayNameFor(model => model.price)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.SKU)
</td>
<td>
#Html.DisplayFor(modelItem => item.product_name)
</td>
<td>
#Html.DisplayFor(modelItem => item.price)
</td>
<td>
#* #Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })*#
</td>
</tr>
}
</table>
So what I want to do is... when an item is clicked, it renders the partial with an new object. Yes, the partial view is only rendered on the same page.
I have been doing so many things. Although I do not think it is such a hard problem, I am not really sure what I need to do for this...
Since you want to update a part of the page you will need to use ajax to accomplish that. You have two options there:
User #Ajax.ActionLink (How can i load Partial view inside the view)
You can write your own jquery ajax request that invokes your controller method and returns the partial view.
It happened to me as well. I wanted the page to be partial and loaded on the same page but it kept forwarding me to other link. Make sure following points are taken care of:
You have included your jquery-1.6.2.js or whatever version of this file you have.
Also make you have included your jquery file you have created. Make sure the above one is included first.
If you have included these files in some section of your .cshtml section then make sure you render it in your _Layout.cshtml or other layout file you are using. For example you have included your file in head section of your index.cshtml like this
#section head{
}
then you have to render this section in _layout.cshtml with #RenderSection("head", required: false)
what you can also do is Make sure that jQuery is not included twice and that you don't have some javascript errors. Look at your javascript console in the browser as well as the Network tab to ensure that all your scripts are included properly.
Good Luck!!!

Categories