My model is recognized by my controller, but not my view - asp.net-mvc

I am working on an MVC project and I added a model to my Model's Folder.
[ProjectName].web.Models.ProductAndClient
That same folder already has another model called 'UserAccount'
When I go to my controller, I can instantiate and use the model normally; I didn't have any issues accessing or seeing the model from the controller.
However, when I go to my view and try to use the model with Razor, it will only show the
[ProjectName].web.Models.UserAccount
option. It will not pull up ProductAndClient. I have other classes in the bll that I can access, as well. Is is just this one class that the View will not see.
I already tried the web config solution in this Stack Overflow solution. It didn't work. Again, the view can already see the model folder, it just wont see the one file.
I have also tried building, cleaning, and rebuilding the solution. I have tried shutting down and restarting Visual Studio. I have tried shutting down and restarting my computer. I have tried deleting and re-creating the class. And I have tried accessing the class from other views. And I triple checked everything says 'public'. None of them work.
As far as the exact 'error', when I type the
#model [projectName].web.Models.ProductAndClient
The 'ProductAndClient' part has a red squiggly under it. And it says that it does not exist in the namespace. I have used this syntax on several other pages in this project and other projects, so It must just be some random thing I did to make this not work.
namespace [projectName].web.Models
{
public class ProductAndClient
{
public ClientInv Client { get; set; } //used as a model for the UI
public List<ClientInv> Clients { get; set; } //collected info
public List<ProductCommon> Products { get; set; } //used to compare description and prices
public List<SelectListItem> ProductNames { get; set; } //used for drop down
}
}
using [projectName].web.Models;
namespace [projectName].web.Controllers
{
public class InvoiceController : Controller
{
public ActionResult Index()
{
//Variables
ProductCommon productCommon = new ProductCommon();
List<string> productNames_String = new List<string>();
ProductAndClient client = new ProductAndClient();
//Other code that does stuff goes here
client.Client = new ClientInv();
client.ProductNames = productNames;
client.Products = products;
return View(client);
}
#model [projectName].web.Models.ProductAndClient

If closing/opening the file doesn't help, try adding a using.
#using [projectName].web.Models
#model ProductAndClient
Or add your model namespace to your web.config
<pages>
<namespaces>
<add namespace="[projectName].web.Models" />
</namespaces>
</pages>

Related

Glass Mapper loads collections only for interfaces

Using Sitecore 10.2 and Glass Mapper 5.8.180
After upgrade from Sitecore 8.2 and switching to above mentioned version of Glass Mapper our code stopped loading collection references. I am aware that in Glass Mapper now the lazy loading is turned on by default and I want to keep this setting.
Problem is with follows:
Having
[SitecoreType(TemplateId = "{...}", AutoMap = true)]
public interface IStatementContainer
{
IEnumerable<Statement> Statements { get; set; }
}
public class StatementContainer : IStatementContainer
{
public virtual IEnumerable<Statement> Statements { get; set; }
}
The following code
_mvcContext.SitecoreService.GetItem<StatementContainer>(datasource)
does not work properly. The Statements are empty.
For following code
_mvcContext.SitecoreService.GetItem<IStatementContainer>(datasource)
the Statements are being loaded properly.
Could you explain me the difference in behavior?
Our legacy code contains a lot of usages of concrete types rather than interfaces, changing all of them would be difficult.

Entity Framework - Code First - Multiple projects

I have one solution with three projects in it:
ToDo.Web
ToDo.Core
ToDo.Data
ToDo.Web is my startup project and is an MVC 4 solution.
ToDo.Core is a Class Library solution and it contains all my classes like User, Task etc.
ToDo.Data is my data repository and contains my ToDoContext model.
My ToDoModel model looks like this:
namespace ToDo.Data
{
public class ToDoModel : DbContext
{
public DbSet<Task> Tasks { get; set; }
public DbSet<User> Users { get; set; }
}
}
I am trying to get the project to create my database on my locally installed SQL Server 2012. So in my web.config (in the ToDo.Web project) I have the following connectionstring:
<add name="ToDo.Data.ToDoModel" connectionString="Data Source=XXX\YYY;Integrated Security=SSPI;initial catalog=ToDo" providerName="System.Data.SqlClient" />
I then try to execute the following command from Package Manager Console:
Enable-Migrations -projectname ToDo.Data -StartUpProjectName ToDo.Web
The command executes nicely with no errors. And I can see a Migrations folder in my ToDo.Data project. But it only contains a Configuration.cs file and no information about my model. And I cannot see the database being created on my SQL server either.
I have tried creating a simple Console application, using the same connection string where it works nicely.
I have tried adding the connection string to my app.config in the ToDo.Data project without luck.
Anyone who can guide me in the right direction?

ASP.NET MVC 3 - Portable Area View doesn't find my model

I've started using MvcContrib's Portable Areas and everything works fine for the very simple views, but when I want to use a custom model in my view i get the error saying the namespace doesn't exist.
The view is set to be embedded as resource. And intellisense in the view recognizes the model just fine.
Does anybody have any idea what might cause the problem?
UPDATE
I think it might have to do with the fact that i'm using MEF to load the plugins. I had a similar problem when loading the controllers. I had to build a custom ControllerFactory that would look in the MEF Controllers list if no suitable controller was found by the default controllerfactory.
UPDATE 2
I managed to get rid of the error by providing the RazorBuildProvider with my MEF-loaded assemblies. However, now the view is not found anymore. If the view is not strongly typed it IS found.
RazorBuildProvider.CodeGenerationStarted += (object sender, EventArgs e) =>
{
RazorBuildProvider provider = (RazorBuildProvider)sender;
foreach (var module in ExternalComponents)
{
provider.AssemblyBuilder.AddAssemblyReference(module.GetType().Assembly);
}
};
Source Code
The Model
namespace Isis.Plugins.TextArea.TextArea.Models
{
public class TextAreaModel
{
[Required(ErrorMessage = "Field is required")]
public string Message { get; set; }
}
}
The Controller:
namespace Isis.Plugins.TextArea.TextArea.Controllers
{
[Export(typeof(IController))]
public class IndexController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View(new TextAreaModel() { Message = "Hallow!" });
}
[HttpGet]
public ActionResult Editor()
{
return View(new TextAreaModel() { Message = "EDITOR CONTENT" });
}
}
}
The View
#model Isis.Plugins.TextArea.TextArea.Models.TextAreaModel
#Model.Message
The error:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0234: The type or namespace name 'Plugins' does not exist in the namespace 'Isis' (are you missing an assembly reference?)
Source Error:
Line 27:
Line 28:
Line 29: public class _Page_Areas_TextArea_Views_Index_Index_cshtml : System.Web.Mvc.WebViewPage<Isis.Plugins.TextArea.TextArea.Models.TextAreaModel> {
Line 30:
Line 31: #line hidden
I'm facing similar issue with MEF & razor view engine (trying similar approach you have described). When i load my strongly typed razor views, i get "are you missing an assembly/reference" error.
I tried deploying my assemblies under Bin but that didnt help either.
Only way to avoid it is to do a loadFrom assembly on RazorBuildProvider.
I couldn't find any documentation on RazorBuildProvider other than "not intended to be used directly from your code"
You're code snippet is quite interesting... can you please explain how it works? Where is this expected to be registered - at AppStart?
RazorBuildProvider.CodeGenerationStarted += (object sender, EventArgs e) =>
{
RazorBuildProvider provider = (RazorBuildProvider)sender;
foreach (var module in ExternalComponents)
{
provider.AssemblyBuilder.AddAssemblyReference(module.GetType().Assembly);
}
};
Any clarity would be much appreciated...
I eventually decided to place all the plugins in the Bin directory instead of a custom Plugins directory. It's not the solution I was aiming for, but it works for now.

L2S DataContext out of synch: row not found or changed

Psssst...!
Read on, by all means. But I can tell you here that the problem had nothing to do with the DataContext, but with Dependency Injection. I have left the question up, as it documents one possible issue with the "row not found or changed error" that has nothing to do with real world concurrency conflicts.
It seems the problems have been caused by badly written dependency injection. Or rather, I am beginning to believe, by default lifecycle management by the DI container I used.
The problem was that I used a DataContext as a constructor argument that was supplied by Ninject. It seems that the default behaviour was to cache this DataContext, leading to all manner of unexpected behaviour. I will ask a separate question about this.
Anyway, what follows is my original question, which as you will see, misses the real cause of the issue by a mile...
The Problem
I am getting a number of errors that imply that the DataContext, or rather, the way I am using the DataContext is getting out of synch.
The error occurs on db.SubmitChanges() where db is my DataContext instance. The error is:
Row not found or changed.
The problem only occurs intermitently, for example, adding a row then deleting it. If I stop the dev server and restart, the added row is there and I can delete it no problem.
Ie, it seems that the problem is related to the DataContext losing track of the rows that have been added.
IMPORTANT:
Before anyone votes to close this thread, on the basis of it being a duplicate, I have checked the sql server profiler and there is no "Where 0 = 1" in the SQL.
I have also recreated the dbml file, so am satisfied that the database schema is in synch with the schema represented by the dbml file.
Ie, no cases of mismatched nullable/not nullable columns, etc.
My Diagnosis (for what it is worth):
The problem seems (to me) related to how I am using the DataContext. I am new to MVC, Repositories and Services patterns, so suspect that I have wired things up wrong.
The Setup
Simple eLearning app in its early stages. Pupils need to be able to add and delete courses (Courses table) to their UserCourses.
To do this, I have a service that gets a specific DataContext instance Dependency Injected into its constructor.
Service Class Constructor:
public class SqlPupilBlockService : IPupilBlockService
{
DataContext db;
public SqlPupilBlockService(DataContext db)
{
this.db = db;
CoursesRepository = new SqlRepository<Course>(db);
UserCoursesRepository = new SqlRepository<UserCourse>(db);
}
// Etc, etc
}
The CoursesRepository and UserCoursesRepository are both private properties of the service class that are of type IRepository (just a simple generic repository interface).
SqlRepository Code:
public class SqlRepository<T> : IRepository<T> where T : class
{
DataContext db;
public SqlRepository(DataContext db)
{
this.db = db;
}
#region IRepository<T> Members
public IQueryable<T> Query
{
get { return db.GetTable<T>(); }
}
public List<T> FetchAll()
{
return Query.ToList();
}
public void Add(T entity)
{
db.GetTable<T>().InsertOnSubmit(entity);
}
public void Delete(T entity)
{
db.GetTable<T>().DeleteOnSubmit(entity);
}
public void Save()
{
db.SubmitChanges();
}
#endregion
}
The two methods for adding and deleting UserCourses are:
Service Methods for Adding and Deleting UserCourses:
public void AddUserCourse(int courseId)
{
UserCourse uc = new UserCourse();
uc.IdCourse = courseId;
uc.IdUser = UserId;
uc.DateCreated = DateTime.Now;
uc.DateAmended = DateTime.Now;
uc.Role = "Pupil";
uc.CourseNotes = string.Empty;
uc.ActiveStepIndex = 0;
UserCoursesRepository.Add(uc);
UserCoursesRepository.Save();
}
public void DeleteUserCourse(int courseId)
{
var uc = (UserCoursesRepository.Query.Where(x => x.IdUser == UserId && x.IdCourse == courseId)).Single();
UserCoursesRepository.Delete(uc);
UserCoursesRepository.Save();
}
Ajax
I am using Ajax via Ajax.BeginForm
I don't think that is relevant.
ASP.NET MVC 3
I am using mvc3, but don't think that is relevant: the errors are related to model code.
The problem only occurs intermitently,
for example, adding a row then
deleting it. If I stop the dev server
and restart, the added row is there
and I can delete it no problem.
Your code does not show what the link is between the Added Row and the Delete/Update. Your Add() doesn't return an object reference.
I'm thinking you are missing a Refresh (ie reload the object after Insert). Is your IdCourse also the PK in the Table?
Edit:
Further research has revealed that the problem is with the dependency injection.
The problem was related to how Dependency Injection manages the items it creates. Google for 'lifecycle management' in IoC or DI. Essentially, DI cached a DataContext constructor argument that I injected.
For a way to solve this using the Factory Pattern, see this thread:
Ninject caching an injected DataContext? Lifecycle Management?
The accepted answer solved it all.

Very Basic StructureMap?

Ok, I wrote this question up earlier today but I decided to delete it because I thought the question wasn't worded very well. I decided to wait until I had more time to compose it at home :).
I am just getting started with IOC/DI. I have done some research on which framework to use and decided to give StructureMap a spin. The following is the first tutorial I used:
http://dimecasts.net/Casts/CastDetails/39 by Derik Whittaker.
Anyways, I got everything working like a dream with EVERYTHING is hosted in the same project.
Here is my sample code:
[PluginFamily("SMTest",IsSingleton=true)]
public interface IVehicle
{
byte TopSpeed {set;get;}
byte MPG { set; get; }
}
[Pluggable("SMTest")]
public class Car : IVehicle
{
private byte mTopSpeed;
private byte mMPG;
#region IVehicle Members
byte IVehicle.TopSpeed
{
get
{
return mTopSpeed;
}
set
{
mTopSpeed = value;
}
}
public interface IConsumer
{
IVehicle Car { get; set; }
}
[Pluggable("SMTest")]
public class Consumer : StructureMapBasic.IConsumer
{
private IVehicle mCar;
public Consumer(IVehicle lcar)
{
Car = lcar;
}
public IVehicle Car { set; get; }
byte IVehicle.MPG
{
get
{
return mMPG;
}
set
{
mMPG = value;
}
}
#endregion
}
So anyways if i create the project above into a command line program and do the following:
var consumer = ObjectFactory.GetInstance<IConsumer>();
It works perfectly. No problems at all. When i create a seperate project in the solution and then change the project above to a DLL. I get the following error:
Test method StructureMapBasic.ConsumerTest.ConsumerConstructorTest
threw exception: StructureMap.StructureMapException: StructureMap
Exception Code: 202 No Default Instance defined for PluginFamily
StructureMapBasic.IConsumer, StructureMapBasic, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null.
At first i thought maybe the StructureMap.Config file didn't get into the new projects bin folder but that wasn't the case. It was there. Everythign compiles just fine this problem happens at runtime. I'm sure the solution is very easy but for the life of me i can't figure out whats going wrong. Any help would be MUCH appreciated.
Thanks,
Ncage
I took me all friggn day to figure this out. At first i thought i was just being an idiot and i was missing something stupid. Well i was not. I thought it was related to different projects but it was not. I created a new console application that consumed my StructureMapped DLL (If just coined a term ;) ). Anyways, after trying to spend all day on this problem i FINALLY found a post that described the problem. its a freakn bug in MSTest (my project i was having problems with was created in MSTest). Xunit here i come. Here is a post that describes the issue from the same guy who created the tutorial video:
http://devlicio.us/blogs/derik_whittaker/archive/2008/07/23/mstest-why-i-hate-you-you-cause-me-too-much-friction.aspx

Resources