The Acumen software design blog provides you with helpful articles about MVC5.

This web site provides a good overview.

Official Microsoft MVC5 Overview

Recently, while trying to implement Bootstrap’s typeahead.js to an ASP.NET MVC project, we ran into a couple problems. To start, we were using the following articles as a guide:

http://deanhume.com/home/blogpost/twitter-bootstrap-typeahead-and-asp-net-mvc—key-value-pairs/88

http://yassershaikh.com/using-twitter-typeahead-js-with-asp-net-mvc-web-api/

The code within these articles worked just fine for the purpose of dealing with in-memory data. For instance, creating a handmade List<Company> would execute without flaws. However, these articles didn’t work for our particular situation because we were dealing with an Entity Framework generated class containing data from a database. This being the case, we figured we could make an equivalent list using an Entity Framework query like so:

var companies = db.Companies.Where(m => m.Name.StartsWith(query)).Select(c => new { c.Name, c.CompanyID });

This turned out to be only half of the battle. We were still having issues so we began logging some JavaScript objects in the console. With the handmade list, the console showed a conventional JSON object. On the other hand, when we passed the Entity Framework JSON serialized object we got numerous errors, including:

A circular reference was detected while serializing an object of type ‘System.Data.Entity.DynamicProxies.Company_983FFFBF6539DF8F813E1EAB1A1565F8743CF808D3B09F748B8A4906B756C4EF’.

We tried manually serializing, but it gave a similar error:

Using JsonConvert.SerializeObject
In Visual Studio before getting to client:
Self referencing loop detected for property ‘Company’ with type ‘System.Data.Entity.DynamicProxies.Company_983FFFBF6539DF8F813E1EAB1A1565F8743CF808D3B09F748B8A4906B756C4EF’. Path ‘[0].SalesCalls[0]’.

So, the big problem was trying to serialize an Entity Framework object. This can be done by changing a particular setting to false. In your code, you can simply call the following:

context.Configuration.ProxyCreationEnabled = false;

After adding that, we had no more issues. Our final action method looked like this:

public ActionResult GetCompanies(string query) {

    // Enable json serialization of the object.
    db.Configuration.ProxyCreationEnabled = false;

    var companies = db.Companies.Where(m => m.Name.StartsWith(query)).Select(c => new { c.Name, c.CompanyID });

    return Json(companies, JsonRequestBehavior.AllowGet);
}

.net MVC

.net mvc

Our .net MVC development team started working with the new Web API 2 controllers released with Visual Studio 2013, and quickly hit some important issues.

Routing and AttributeRouting and using Web API 2 controllers inside an Area in an ASP.NET MVC5 project

Currently, this IS possible. It was not possible with Web API and it seems like it was also not possible in beta, but this can be done with Web API 2 and MVC 5. I used the following configurations:

 // File: ~/Areas/API/APIAreaRegistration.cs
    using System.Web.Http;
    using System.Web.Mvc;

    namespace MySolution.Areas.API {
        public class APIAreaRegistration : AreaRegistration {
            public override string AreaName {
                get {
                    return "API";
                }
            }

            public override void RegisterArea(AreaRegistrationContext context) {
                context.Routes.MapMvcAttributeRoutes();
                context.Routes.MapHttpRoute(
                    name: this.AreaName,
                    routeTemplate: this.AreaName + "/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }
 // File: ~/Global.asax.cs
    using System.Linq;
    using System.Web.Http;
    using System.Web.Mvc;
    using System.Web.Routing;
    using Newtonsoft.Json.Serialization;
    using WebMatrix.WebData;
    using AcumenSystem5.Models;
    using System.Threading;
    using System.Web.Optimization;

    namespace MySolution {
        public class MvcApplication : System.Web.HttpApplication {
            protected void Application_Start() {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(config => { // This HAS to be here. Having it last caused routing to not work.
                    config.MapHttpAttributeRoutes(); // This allows us to use AttributeRouting

                    // This sets JSON as the default return format and removes any circular references
                    var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
                    config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
                    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
                    json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
                });
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
            }
        }
    }

AttributeRouting and WebAPI Routing not working correctly and returning 404 Errors – .net MVC

After struggling with areas, I hit this issue when adding the Web API 2 controller to the root controllers folder. I discovered that the ordering of configuration mattered. So, like as shown in the Global.asax.cs above, the order needs to be as follows to work correctly:
protected void Application_Start() {

     // Full file code in example above
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(config => { // This HAS to be here. Having it last caused routing to not work.
            config.MapHttpAttributeRoutes(); // This allows us to use AttributeRouting

            config.Routes.MapHttpRoute( // This allows us to use conventional HTTP routing
                    name: "Name",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                ); ;

            // This sets JSON as the default return format and removes any circular references
            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
        });
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
    }

Hope this helps!

Check out our ASP.NET MVC to see what we can do for you.

For more information on .net MVC, click on the link below:

https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/asp-net-mvc-routing-overview-cs

Recently, while developing an application using Entity Framework, I ran into several compilation errors after adding an additional table to my database. Most notably was this error when trying to declare a couple of variables that had once worked before:

Compiler Error Message: CS1061: … does not contain a definition for … and no extension method … accepting a first argument of type … could be found (are you missing a using directive or an assembly reference?)

When searching around in my .edmx file for reasons as to why my relationships were not working, I ran into this message under the mapping details:

“Mappings are not allowed for an association over exposed foreign keys.”

I wanted to note that this message is not relevant to the issue at hand. After I solved the problem, I still received this message.

I quickly realized that the error had to do with the relationships between tables that I had previously established. When I had added the new table, I deleted the diagram from my .edmx file and updated the model from the database like I normally do when adding a new table. However, this time, Entity Framework did not properly regenerate the code associated with my database. Each property was stored as a class member within the entity class as expected, but my relationships were not. This was despite the fact that my .edmx diagram showed the relationships exactly as they should be.

After hours of Googling different phrases and errors, I ran into this ticket

As it turns out, this is a bug with Entity Framework inside of VS2012, and if your Visual Studio is out of date, you are likely to experience it. Because of this bug, if your .edmx file is nested within a project folder, Entity Framework will sometimes fail to generate code properly. Fortunately, the solution is much easier to implement than it is to find. You can do any of the following:

  • Update your Visual Studios here
  • Right click on the .tt file and select “Run Custom Tool”.
  • Drag the .edmx file out of the project folder.