Search Results

Search found 9325 results on 373 pages for 'mvc'.

Page 5/373 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Good tutorial for ASP.net mvc 2

    - by Ben Robinson
    I am an experienced asp.net web forms developer using c# but i have never used asp.net MVC. As I am just starting out with mvc i would like to start with mvc 2. I am looking for a good intro/tutorial to help me understand the basics. I am aware of the Nerd Dinner but that is based around MVC 1. What would you guys recomend for me to get started. Should i work through the nerd dinner tutorial then once i have a good understanding of mvc then research the new features of mvc 2 or is there a similar getting started tutorial for mvc 2. Sugestions of good books to read are also welcome. In fact any advice on getting started on mvc 2 would be good.

    Read the article

  • CompliationLock throws HttpException when registering areas for ASP.NET MVC unit tests

    - by patridge
    The moment I added a unit test to my ASP.NET MVC application to test some of the area routing, I got an HttpException coming out of the System.Web.Complication.CompilationLock type initializer with the following stack trace. System.Web.HttpException : The type initializer for 'System.Web.Compilation.CompilationLock' threw an exception. ----> System.TypeInitializationException : The type initializer for 'System.Web.Compilation.CompilationLock' threw an exception. ----> System.NullReferenceException : Object reference not set to an instance of an object. at System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() at System.Web.Compilation.BuildManager.GetReferencedAssemblies() at System.Web.Mvc.BuildManagerWrapper.System.Web.Mvc.IBuildManager.GetReferencedAssemblies() at System.Web.Mvc.TypeCacheUtil.FilterTypesInAssemblies(IBuildManager buildManager, Predicate`1 predicate) at System.Web.Mvc.TypeCacheUtil.GetFilteredTypesFromAssemblies(String cacheName, Predicate`1 predicate, IBuildManager buildManager) at System.Web.Mvc.AreaRegistration.RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, Object state) at System.Web.Mvc.AreaRegistration.RegisterAllAreas(Object state) at System.Web.Mvc.AreaRegistration.RegisterAllAreas() at StpWeb.MvcApplication.RegisterRoutes(RouteCollection routes) in Global.asax.cs: line 16 at StpWeb.Tests.RoutesTest.TestFixtureSetUp() in RoutesTest.cs: line 11 --TypeInitializationException at System.Web.Compilation.CompilationLock.GetLock(ref Boolean gotLock) at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() --NullReferenceException at System.Web.Compilation.CompilationLock..cctor()

    Read the article

  • Controller Index methods with different signatures

    - by Narsil
    I am trying to get my URLs in files/id format. I am guessing I should have two Index methods in my controller, one with a parameter and one with not. But I get this error message in browser below. Anyway here is my controller methods: public ActionResult Index() { return Content("Index "); } // // GET: /Files/5 public ActionResult Index(int id) { File file = fileRepository.GetFile(id); if (file == null) return Content("Not Found"); return Content(file.FileID.ToString()); } Error: Server Error in '/' Application. The current request for action 'Index' on controller type 'FilesController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult Index() on type FileHosting.Controllers.FilesController System.Web.Mvc.ActionResult Index(Int32) on type FileHosting.Controllers.FilesController Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Reflection.AmbiguousMatchException: The current request for action 'Index' on controller type 'FilesController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult Index() on type FileHosting.Controllers.FilesController System.Web.Mvc.ActionResult Index(Int32) on type FileHosting.Controllers.FilesController Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [AmbiguousMatchException: The current request for action 'Index' on controller type 'FilesController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult Index() on type FileHosting.Controllers.FilesController System.Web.Mvc.ActionResult Index(Int32) on type FileHosting.Controllers.FilesController] System.Web.Mvc.ActionMethodSelector.FindActionMethod(ControllerContext controllerContext, String actionName) +396292 System.Web.Mvc.ReflectedControllerDescriptor.FindAction(ControllerContext controllerContext, String actionName) +62 System.Web.Mvc.ControllerActionInvoker.FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, String actionName) +13 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +99 System.Web.Mvc.Controller.ExecuteCore() +105 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +39 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7 System.Web.Mvc.<c_DisplayClass8.b_4() +34 System.Web.Mvc.Async.<c_DisplayClass1.b_0() +21 System.Web.Mvc.Async.<c__DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult1.End() +59 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +44 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +7 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8677678 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

    Read the article

  • What are the definitive guidelines for custom Error Handling in ASP.NET MVC 3?

    - by RyanW
    The process of doing custom error handling in ASP.NET MVC (3 in this case) seems to be incredibly neglected. I've read through the various questions and answers here, on the web, help pages for various tools (like Elmah), but I feel like I've gone in a complete circle and still don't have the best solution. With your help, perhaps we can set a new standard approach for error handling. I'd like to keep things simple and not over-engineer this. Here are my goals: For Server errors/exceptions: Display debugging information in dev Display friendly error page in production Log errors and email them to administrator in production Return 500 HTTP Status Code For 404 Not Found errors: Display friendly error page Log errors and email them to administrator in production Return 404 HTTP Status Code Is there a way to meet these goals with ASP.NET MVC?

    Read the article

  • Odd MVC 4 Beta Razor Designer Issue

    - by Rick Strahl
    This post is a small cry for help along with an explanation of a problem that is hard to describe on twitter or even a connect bug and written in hopes somebody has seen this before and any ideas on what might cause this. Lots of helpful people had comments on Twitter for me, but they all assumed that the code doesn't run, which is not the case - it's a designer issue. A few days ago I started getting some odd problems in my MVC 4 designer for an app I've been working on for the past 2 weeks. Basically the MVC 4 Razor designer keeps popping me errors, about the call signature to various Html Helper methods being incorrect. It also complains about the ViewBag object and not supporting dynamic requesting to load assemblies into the project. Here's what the designer errors look like: You can see the red error underlines under the ViewBag and an Html Helper I plopped in at the top to demonstrate the behavior. Basically any HtmlHelper I'm accessing is showing the same errors. Note that the code *runs just fine* - it's just the designer that is complaining with Errors. What's odd about this is that *I think* this started only a few days ago and nothing consequential that I can think of has happened to the project or overall installations. These errors aren't critical since the code runs but pretty annoying especially if you're building and have .csHtml files open in Visual Studio mixing these fake errors with real compiler errors. What I've checked Looking at the errors it indeed looks like certain references are missing. I can't make sense of the Html Helpers error, but certainly the ViewBag dynamic error looks like System.Core or Microsoft.CSharp assemblies are missing. Rest assured they are there and the code DOES run just fine at runtime. This is a designer issue only. I went ahead and checked the namespaces that MVC has access to in Razor which lives in the Views folder's web.config file: /Views/web.config For good measure I added <system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, <split for layout> Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Linq" /> <add namespace="System.Linq.Expressions" /> <add namespace="ClassifiedsBusiness" /> <add namespace="ClassifiedsWeb"/> <add namespace="Westwind.Utilities" /> <add namespace="Westwind.Web" /> <add namespace="Westwind.Web.Mvc" /> </namespaces> </pages> </system.web.webPages.razor> For good measure I added System.Linq and System.Linq.Expression on which some of the Html.xxxxFor() methods rely, but no luck. So, has anybody seen this before? Any ideas on what might be causing these issues only at design time rather, when the final compiled code runs just fine?© Rick Strahl, West Wind Technologies, 2005-2012Posted in Razor  MVC   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Dependency Injection in ASP.NET MVC NerdDinner App using Ninject

    - by shiju
    In this post, I am applying Dependency Injection to the NerdDinner application using Ninject. The controllers of NerdDinner application have Dependency Injection enabled constructors. So we can apply Dependency Injection through constructor without change any existing code. A Dependency Injection framework injects the dependencies into a class when the dependencies are needed. Dependency Injection enables looser coupling between classes and their dependencies and provides better testability of an application and it removes the need for clients to know about their dependencies and how to create them. If you are not familiar with Dependency Injection and Inversion of Control (IoC), read Martin Fowler’s article Inversion of Control Containers and the Dependency Injection pattern. The Open Source Project NerDinner is a great resource for learning ASP.NET MVC.  A free eBook provides an end-to-end walkthrough of building NerdDinner.com application. The free eBook and the Open Source Nerddinner application are extremely useful if anyone is trying to lean ASP.NET MVC. The first release of  Nerddinner was as a sample for the first chapter of Professional ASP.NET MVC 1.0. Currently the application is updating to ASP.NET MVC 2 and you can get the latest source from the source code tab of Nerddinner at http://nerddinner.codeplex.com/SourceControl/list/changesets. I have taken the latest ASP.NET MVC 2 source code of the application and applied  Dependency Injection using Ninject and Ninject extension Ninject.Web.Mvc.Ninject &  Ninject.Web.MvcNinject is available at http://github.com/enkari/ninject and Ninject.Web.Mvc is available at http://github.com/enkari/ninject.web.mvcNinject is a lightweight and a great dependency injection framework for .NET.  Ninject is a great choice of dependency injection framework when building ASP.NET MVC applications. Ninject.Web.Mvc is an extension for ninject which providing integration with ASP.NET MVC.Controller constructors and dependencies of NerdDinner application Listing 1 – Constructor of DinnersController  public DinnersController(IDinnerRepository repository) {     dinnerRepository = repository; }  Listing 2 – Constrcutor of AccountControllerpublic AccountController(IFormsAuthentication formsAuth, IMembershipService service) {     FormsAuth = formsAuth ?? new FormsAuthenticationService();     MembershipService = service ?? new AccountMembershipService(); }  Listing 3 – Constructor of AccountMembership – Concrete class of IMembershipService public AccountMembershipService(MembershipProvider provider) {     _provider = provider ?? Membership.Provider; }    Dependencies of NerdDinnerDinnersController, RSVPController SearchController and ServicesController have a dependency with IDinnerRepositiry. The concrete implementation of IDinnerRepositiry is DinnerRepositiry. AccountController has dependencies with IFormsAuthentication and IMembershipService. The concrete implementation of IFormsAuthentication is FormsAuthenticationService and the concrete implementation of IMembershipService is AccountMembershipService. The AccountMembershipService has a dependency with ASP.NET Membership Provider. Dependency Injection in NerdDinner using NinjectThe below steps will configure Ninject to apply controller injection in NerdDinner application.Step 1 – Add reference for NinjectOpen the  NerdDinner application and add  reference to Ninject.dll and Ninject.Web.Mvc.dll. Both are available from http://github.com/enkari/ninject and http://github.com/enkari/ninject.web.mvcStep 2 – Extend HttpApplication with NinjectHttpApplication Ninject.Web.Mvc extension allows integration between the Ninject and ASP.NET MVC. For this, you have to extend your HttpApplication with NinjectHttpApplication. Open the Global.asax.cs and inherit your MVC application from  NinjectHttpApplication instead of HttpApplication.   public class MvcApplication : NinjectHttpApplication Then the Application_Start method should be replace with OnApplicationStarted method. Inside the OnApplicationStarted method, call the RegisterAllControllersIn() method.   protected override void OnApplicationStarted() {     AreaRegistration.RegisterAllAreas();     RegisterRoutes(RouteTable.Routes);     ViewEngines.Engines.Clear();     ViewEngines.Engines.Add(new MobileCapableWebFormViewEngine());     RegisterAllControllersIn(Assembly.GetExecutingAssembly()); }  The RegisterAllControllersIn method will enables to activating all controllers through Ninject in the assembly you have supplied .We are passing the current assembly as parameter for RegisterAllControllersIn() method. Now we can expose dependencies of controller constructors and properties to request injectionsStep 3 – Create Ninject ModulesWe can configure your dependency injection mapping information using Ninject Modules.Modules just need to implement the INinjectModule interface, but most should extend the NinjectModule class for simplicity. internal class ServiceModule : NinjectModule {     public override void Load()     {                    Bind<IFormsAuthentication>().To<FormsAuthenticationService>();         Bind<IMembershipService>().To<AccountMembershipService>();                  Bind<MembershipProvider>().ToConstant(Membership.Provider);         Bind<IDinnerRepository>().To<DinnerRepository>();     } } The above Binding inforamtion specified in the Load method tells the Ninject container that, to inject instance of DinnerRepositiry when there is a request for IDinnerRepositiry and  inject instance of FormsAuthenticationService when there is a request for IFormsAuthentication and inject instance of AccountMembershipService when there is a request for IMembershipService. The AccountMembershipService class has a dependency with ASP.NET Membership provider. So we configure that inject the instance of Membership Provider. When configuring the binding information, you can specify the object scope in you application.There are four built-in scopes available in Ninject:Transient  -  A new instance of the type will be created each time one is requested. (This is the default scope). Binding method is .InTransientScope()   Singleton - Only a single instance of the type will be created, and the same instance will be returned for each subsequent request. Binding method is .InSingletonScope()Thread -  One instance of the type will be created per thread. Binding method is .InThreadScope() Request -  One instance of the type will be created per web request, and will be destroyed when the request ends. Binding method is .InRequestScope() Step 4 – Configure the Ninject KernelOnce you create NinjectModule, you load them into a container called the kernel. To request an instance of a type from Ninject, you call the Get() extension method. We can configure the kernel, through the CreateKernel method in the Global.asax.cs. protected override IKernel CreateKernel() {     var modules = new INinjectModule[]     {         new ServiceModule()     };       return new StandardKernel(modules); } Here we are loading the Ninject Module (ServiceModule class created in the step 3)  onto the container called the kernel for performing dependency injection.Source CodeYou can download the source code from http://nerddinneraddons.codeplex.com. I just put the modified source code onto CodePlex repository. The repository will update with more add-ons for the NerdDinner application.

    Read the article

  • New Validation Attributes in ASP.NET MVC 3 Future

    - by imran_ku07
         Introduction:             Validating user inputs is an very important step in collecting information from users because it helps you to prevent errors during processing data. Incomplete or improperly formatted user inputs will create lot of problems for your application. Fortunately, ASP.NET MVC 3 makes it very easy to validate most common input validations. ASP.NET MVC 3 includes Required, StringLength, Range, RegularExpression, Compare and Remote validation attributes for common input validation scenarios. These validation attributes validates most of your user inputs but still validation for Email, File Extension, Credit Card, URL, etc are missing. Fortunately, some of these validation attributes are available in ASP.NET MVC 3 Future. In this article, I will show you how to leverage Email, Url, CreditCard and FileExtensions validation attributes(which are available in ASP.NET MVC 3 Future) in ASP.NET MVC 3 application.       Description:             First of all you need to download ASP.NET MVC 3 RTM Source Code from here. Then extract all files in a folder. Then open MvcFutures project from mvc3-rtm-sources\mvc3\src\MvcFutures folder. Build the project. In case, if you get compile time error(s) then simply remove the reference of System.Web.WebPages and System.Web.Mvc assemblies and add the reference of System.Web.WebPages and System.Web.Mvc 3 assemblies again but from the .NET tab and then build the project again, it will create a Microsoft.Web.Mvc assembly inside mvc3-rtm-sources\mvc3\src\MvcFutures\obj\Debug folder. Now we can use Microsoft.Web.Mvc assembly inside our application.             Create a new ASP.NET MVC 3 application. For demonstration purpose, I will create a dummy model UserInformation. So create a new class file UserInformation.cs inside Model folder and add the following code,   public class UserInformation { [Required] public string Name { get; set; } [Required] [EmailAddress] public string Email { get; set; } [Required] [Url] public string Website { get; set; } [Required] [CreditCard] public string CreditCard { get; set; } [Required] [FileExtensions(Extensions = "jpg,jpeg")] public string Image { get; set; } }             Inside UserInformation class, I am using Email, Url, CreditCard and FileExtensions validation attributes which are defined in Microsoft.Web.Mvc assembly. By default FileExtensionsAttribute allows png, jpg, jpeg and gif extensions. You can override this by using Extensions property of FileExtensionsAttribute class.             Then just open(or create) HomeController.cs file and add the following code,   public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(UserInformation u) { return View(); } }             Next just open(or create) Index view for Home controller and add the following code,  @model NewValidationAttributesinASPNETMVC3Future.Model.UserInformation @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Index</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>UserInformation</legend> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Email) </div> <div class="editor-field"> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class="editor-label"> @Html.LabelFor(model => model.Website) </div> <div class="editor-field"> @Html.EditorFor(model => model.Website) @Html.ValidationMessageFor(model => model.Website) </div> <div class="editor-label"> @Html.LabelFor(model => model.CreditCard) </div> <div class="editor-field"> @Html.EditorFor(model => model.CreditCard) @Html.ValidationMessageFor(model => model.CreditCard) </div> <div class="editor-label"> @Html.LabelFor(model => model.Image) </div> <div class="editor-field"> @Html.EditorFor(model => model.Image) @Html.ValidationMessageFor(model => model.Image) </div> <p> <input type="submit" value="Save" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div>             Now just run your application. You will find that both client side and server side validation for the above validation attributes works smoothly.                      Summary:             Email, URL, Credit Card and File Extension input validations are very common. In this article, I showed you how you can validate these input validations into your application. I explained this with an example. I am also attaching a sample application which also includes Microsoft.Web.Mvc.dll. So you can add a reference of Microsoft.Web.Mvc assembly directly instead of doing any manual work. Hope you will enjoy this article too.   SyntaxHighlighter.all()

    Read the article

  • ASP.NET MVC 2 throws exception for ‘favicon.ico’

    - by nmarun
    I must be on fire or something – third blog in 2 days… awesome! Before I begin, in case you’re wondering, favicon.ico is the small image that appears to the left of your web address, once the page loads. In order to learn more about MVC or any thing for that matter, it’s better to look at the source itself. Since MVC is open source (at least some part of it is), I started looking at the source code that’s available for download. While doing so, I hit Steve Sanderson’s blog site where he explains in great detail the way to debug your app using ASP.NET MVC source code. For those who are not aware, Steve Sanderson’s book - Pro ASP.NET MVC Framework, is one of the best books to learn about MVC. Alrighty, I followed the article and I hit F5 to debug the default / unchanged MVC project. I put a breakpoint in the DefaultControllerFactory.cs, CreateController() method. To know a little more about this class and the method, read this. Sure enough, the control stopped at the breakpoint and I hit F5 again and the page rendered just fine. But then what’s this? The breakpoint was hit again, as if something else was being requested. I now hovered my mouse over the ‘controllerName’ parameter and it says – favicon.ico. This by itself was more than enough for me to raise my eye-brows, but what happened next just took the ground below my feet. Oh, oh, I’m sorry I’m just typing, no code, no image, so here are a couple of screen captures. The first one shows the request for the Home controller; I get ‘Home’ when I hover over the parameter: And here’s the one that shows the same for call for ‘favicon.ico’. So, I step through the code and when the control reaches line 91 – GetControllerInstance() method, I step in. This is when I had the ‘ground-losing’ experience. Wow, an exception is being thrown for this file and that too in RTM. For some reason MVC thinks, this as a controller and tries to run it through the MvcHandler and it hits this snag. So it seems like this will happen for any MVC 2 site and this did not happen for me in the previous version of MVC. Before I get to how to resolve it, here’s another way of reproducing this exception. Revert back all your changes that you did as mentioned in Steve’s blog above. Now, add a class to your MVC project and call it say, MyControllerFactory and let this inherit from DefaultControllerFactory class. (Read this for details on the DefaultControllerFactory class is and how it is used in a different context). Add an override for the CreateController() method and for the sake of this blog, just copy the same content from the DefaultControllerFactory class. The last step is to tell your MVC app to use the MyControllerFactory class instead of the default one. To do this, go to your Global.asax.cs file and add line 6 of the snippet below: 1: protected void Application_Start() 2: { 3: AreaRegistration.RegisterAllAreas(); 4:   5: RegisterRoutes(RouteTable.Routes); 6: ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory()); 7: } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Now, you’re ready to reproduce the issue. Just F5 the project and when you hit the overridden CreateController() method for the second time, this is what it looks like for me: And continuing further gives me the same exception. I believe this is something that MS should fix, as not having ‘favicon.ico’ file will be common for most of the applications. So I think the when you create an MVC project, line 6 should be added by default by Visual Studio itself: 1: public class MvcApplication : System.Web.HttpApplication 2: { 3: public static void RegisterRoutes(RouteCollection routes) 4: { 5: routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 6: routes.IgnoreRoute("favicon.ico"); 7:   8: routes.MapRoute( 9: "Default", // Route name 10: "{controller}/{action}/{id}", // URL with parameters 11: new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 12: ); 13: } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } There it is, that’s the solution to avoid the exception altogether. I tried this both IE8 and Firefox browsers and was able to successfully reproduce the error. Hope someone will look at this issue and find a fix. Just before I finish up, I found another ‘bug’, if you want to call it, with Visual Studio 2008. Remember how you could change what browser you want your application to run in by just right clicking on the .aspx file and choosing ‘Browse with…’? Seems like that’s missing when you’re working with an MVC project. In order to test the above bug in the other browser, I had to load a classic ASP.NET project, change the settings and then run my MVC project. Felt kinda ‘icky’, for lack of a better word.

    Read the article

  • Physical Directories vs. MVC View Paths

    - by Rick Strahl
    This post falls into the bucket of operator error on my part, but I want to share this anyway because it describes an issue that has bitten me a few times now and writing it down might keep it a little stronger in my mind. I've been working on an MVC project the last few days, and at the end of a long day I accidentally moved one of my View folders from the MVC Root Folder to the project root. It must have been at the very end of the day before shutting down because tests and manual site navigation worked fine just before I quit for the night. I checked in changes and called it a night. Next day I came back, started running the app and had a lot of breaks with certain views. Oddly custom routes to these controllers/views worked, but stock /{controller}/{action} routes would not. After a bit of spelunking I realized that "Hey one of my View Folders is missing", which made some sense given the error messages I got. I looked in the recycle bin - nothing there, so rather than try to figure out what the hell happened, just restored from my last SVN checkin. At this point the folders are back… but… view access  still ends up breaking for this set of views. Specifically I'm getting the Yellow Screen of Death with: CS0103: The name 'model' does not exist in the current context Here's the full error: Server Error in '/ClassifiedsWeb' Application. Compilation ErrorDescription: 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: CS0103: The name 'model' does not exist in the current contextSource Error: Line 1: @model ClassifiedsWeb.EntryViewModel Line 2: @{ Line 3: ViewBag.Title = Model.Entry.Title + " - " + ClassifiedsBusiness.App.Configuration.ApplicationName; Source File: c:\Projects2010\Clients\GorgeNet\Classifieds\ClassifiedsWeb\Classifieds\Show.cshtml    Line: 1 Compiler Warning Messages: Show Detailed Compiler Output: Show Complete Compilation Source: Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272 Here's what's really odd about this error: The views now do exist in the /Views/Classifieds folder of the project, but it appears like MVC is trying to execute the views directly. This is getting pretty weird, man! So I hook up some break points in my controllers to see if my controller actions are getting fired - and sure enough it turns out they are not - but only for those views that were previously 'lost' and then restored from SVN. WTF? At this point I'm thinking that I must have messed up one of the config files, but after some more spelunking and realizing that all the other Controller views work, I give up that idea. Config's gotta be OK if other controllers and views are working. Root Folders and MVC Views don't mix As I mentioned the problem was the fact that I inadvertantly managed to drag my View folder to the root folder of the project. Here's what this looks like in my FUBAR'd project structure after I copied back /Views/Classifieds folder from SVN: There's the actual root folder in the /Views folder and the accidental copy that sits of the root. I of course did not notice the /Classifieds folder at the root because it was excluded and didn't show up in the project. Now, before you call me a complete idiot remember that this happened by accident - an accidental drag probably just before shutting down for the night. :-) So why does this break? MVC should be happy with views in the /Views/Classifieds folder right? While MVC might be happy, IIS is not. The fact that there is a physical folder on disk takes precedence over MVC's routing. In other words if a URL exists that matches a route the pysical path is accessed first. What happens here is that essentially IIS is trying to execute the .cshtml pages directly without ever routing to the Controller methods. In the error page I showed above my clue should have been that the view was served as: c:\Projects2010\Clients\GorgeNet\Classifieds\ClassifiedsWeb\Classifieds\Show.cshtml rather than c:\Projects2010\Clients\GorgeNet\Classifieds\ClassifiedsWeb\Views\Classifieds\Show.cshtml But of course I didn't notice that right away, just skimming to the end and looking at the file name. The reason that /classifieds/list actually fires that file is that the ASP.NET Web Pages engine looks for physical files on disk that match a path. IOW, when calling Web Pages you drop the .cshtml off the Razor page and IIS will serve that just fine. So: /classifieds/list looks and tries to find /classifieds/list.cshtml and executes that script. And that is exactly what's happening. Web Pages is trying to execute the .cshtml file and it fails because Web Pages knows nothing about the @model tag which is an MVC specific template extension. This is why my breakpoints in the controller methods didn't fire and it also explains why the error mentions that the @model key word is invalid (@model is an MVC provided template enhancement to the Razor Engine). The solution of course is super simple: Delete the accidentally created root folder and the problem is solved. Routing and Physical Paths I've run into problems with this before actually. In the past I've had a number of applications that had a physical /Admin folder which also would conflict with an MVC Admin controller. More than once I ended up wondering why the index route (/Admin/) was not working properly. If a physical /Admin folder exists /Admin will not route to the Index action (or whatever default action you have set up, but instead try to list the directory or show the default document in the folder. The only way to force the index page through MVC is to explicitly use /Admin/Index. Makes perfect sense once you realize the physical folder is there, but that's easy to forget in an MVC application. As you might imagine after a few times of running into this I gave up on the Admin folder and moved everything into MVC views to handle those operations. Still it's one of those things that can easily bite you, because the behavior and error messages seem to point at completely different  problems. Moral of the story is: If you see routing problems where routes are not reaching obvious controller methods, always check to make sure there's isn't a physical path being mapped by IIS instead. That way you won't feel stupid like I did after trying a million things for about an hour before discovering my sloppy mousing behavior :-)© Rick Strahl, West Wind Technologies, 2005-2012Posted in MVC   IIS7   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • How can I know which Area my MVC controller action is being called in?

    - by kripto_ash
    I want to know how, from a controller action, I could identify the area in which the controller is in via the MVC framework (I mean, without making all controllers in a given area inherit from a base controller with that info). I'm particularly interested in the case of child actions (controller actions rendered via RenderAction), the area of the calling parent controller for instance. I'm using ASP .NET MVC 2.0 RTM

    Read the article

  • Is ASP.NET MVC is really MVC? Or how to separate model from controller?

    - by Andrey
    Hi all, This question is a bit rhetorical. At some point i got a feeling that ASP.NET MVC is not that authentic implementation of MVC pattern. Or i didn't understood it. Consider following domain: electric bulb, switch and motion detector. They are connected together and when you enter the room motion detector switches on the bulb. If i want to represent them as MVC: switch is model, because it holds the state and contains logic bulb is view, because it presents the state of model to human motion detector is controller, because it converts user actions to generic model commands Switch has one private field (On/Off) as a State and two methods (PressOn, PressOff). If you call PressOn when it is Off it goes to On, if you call it again state doesn't change. Bulb can be replaced with buzzer, motion detector with timer or button, but the model still represent the same logic. Eventually system will have same behavior. This is how i understand classical MVC decomposition, please correct me if i am wrong. Now let's decompose it in ASP.Net MVC way. Bulb is still a view Controller will be switch + motion detector Model is some object that will just pass state to bulb. So the logic that defines behavior moves to controller. Question 1: Is my understanding of MVC and ASP.NET MVC correct? Question 2: If yes, do you agree that ASP.NET MVC is not 100% accurate implementation? And back to life. The final question is how to separate model from controller in case of ASP.NET MVC. There can be two extremes. Controller does basic stuff and call model to do all the logic. Another is controller does all the logic and model is just something like class with properties that is mapped to DB. Question 3: Where should i draw the line between this extremes? How to balance? Thanks, Andrey

    Read the article

  • Integrating ASP.NET MVC 3 into existing upgraded ASP.NET 4 Web Forms applications

    - by SAMIR BHOGAYTA
    http://www.hanselman.com/blog/IntegratingASPNETMVC3IntoExistingUpgradedASPNET4WebFormsApplications.aspx As per above article I follow the steps to integrate WebApp with MVC application. I am successfully integrated MVC project into WebApp(C#) and also VB.NET MVC and VB.NET WebApp also I am able to successfully integrated. The problem is If I choose WebApp as VB.NET project, and integrated with C# MVC project. In this case the request is not routing to corresponding MVC files. What could be the reason not routing to MVC. Do we need to plug some extra dlls?

    Read the article

  • Using GridView and DetailsView in ASP.NET MVC - Part 1

    - by bipinjoshi
    For any beginner in ASP.NET MVC the first disappointment is possibly the lack of any server controls. ASP.NET MVC divides the entire processing logic into three distinct parts namely model, view and controller. In the process views (that represent UI under MVC architecture) need to sacrifice three important features of web forms viz. Postbacks, ViewState and rich event model. Though server controls are not a recommended choice under ASP.NET MVC there are situations where you may need to use server controls. In this two part article I am going to explain, as an example, how GridView and DetailsView can be used in ASP.NET MVC without breaking the MVC pattern.http://www.bipinjoshi.net/articles/59b91531-3fb2-4504-84a4-9f52e2d65c20.aspx 

    Read the article

  • Announcing ASP.NET MVC 3 (Release Candidate 2)

    - by ScottGu
    Earlier today the ASP.NET team shipped the final release candidate (RC2) for ASP.NET MVC 3.  You can download and install it here. Almost there… Today’s RC2 release is the near-final release of ASP.NET MVC 3, and is a true “release candidate” in that we are hoping to not make any more code changes with it.  We are publishing it today so that people can do final testing with it, let us know if they find any last minute “showstoppers”, and start updating their apps to use it.  We will officially ship the final ASP.NET MVC 3 “RTM” build in January. Works with both VS 2010 and VS 2010 SP1 Beta Today’s ASP.NET MVC 3 RC2 release works with both the shipping version of Visual Studio 2010 / Visual Web Developer 2010 Express, as well as the newly released VS 2010 SP1 Beta.  This means that you do not need to install VS 2010 SP1 (or the SP1 beta) in order to use ASP.NET MVC 3.  It works just fine with the shipping Visual Studio 2010.  I’ll do a blog post next week, though, about some of the nice additional feature goodies that come with VS 2010 SP1 (including IIS Express and SQL CE support within VS) which make the dev experience for both ASP.NET Web Forms and ASP.NET MVC even better. Bugs and Perf Fixes Today’s ASP.NET MVC 3 RC2 build contains many bug fixes and performance optimizations.  Our latest performance tests indicate that ASP.NET MVC 3 is now faster than ASP.NET MVC 2, and that existing ASP.NET MVC applications will experience a slight performance increase when updated to run using ASP.NET MVC 3. Final Tweaks and Fit-N-Finish In addition to bug fixes and performance optimizations, today’s RC2 build contains a number of last-minute feature tweaks and “fit-n-finish” changes for the new ASP.NET MVC 3 features.  The feedback and suggestions we’ve received during the public previews has been invaluable in guiding these final tweaks, and we really appreciate people’s support in sending this feedback our way.  Below is a short-list of some of the feature changes/tweaks made between last month’s ASP.NET MVC 3 RC release and today’s ASP.NET MVC 3 RC2 release: jQuery updates and addition of jQuery UI The default ASP.NET MVC 3 project templates have been updated to include jQuery 1.4.4 and jQuery Validation 1.7.  We are also excited to announce today that we are including jQuery UI within our default ASP.NET project templates going forward.  jQuery UI provides a powerful set of additional UI widgets and capabilities.  It will be added by default to your project’s \scripts folder when you create new ASP.NET MVC 3 projects. Improved View Scaffolding The T4 templates used for scaffolding views with the Add-View dialog now generates views that use Html.EditorFor instead of helpers such as Html.TextBoxFor. This change enables you to optionally annotate models with metadata (using data annotation attributes) to better customize the output of your UI at runtime. The Add View scaffolding also supports improved detection and usage of primary key information on models (including support for naming conventions like ID, ProductID, etc).  For example: the Add View dialog box uses this information to ensure that the primary key value is not scaffold as an editable form field, and that links between views are auto-generated correctly with primary key information. The default Edit and Create templates also now include references to the jQuery scripts needed for client validation.  Scaffold form views now support client-side validation by default (no extra steps required).  Client-side validation with ASP.NET MVC 3 is also done using an unobtrusive javascript approach – making pages fast and clean. [ControllerSessionState] –> [SessionState] ASP.NET MVC 3 adds support for session-less controllers.  With the initial RC you used a [ControllerSessionState] attribute to specify this.  We shortened this in RC2 to just be [SessionState]: Note that in addition to turning off session state, you can also set it to be read-only (which is useful for webfarm scenarios where you are reading but not updating session state on a particular request). [SkipRequestValidation] –> [AllowHtml] ASP.NET MVC includes built-in support to protect against HTML and Cross-Site Script Injection Attacks, and will throw an error by default if someone tries to post HTML content as input.  Developers need to explicitly indicate that this is allowed (and that they’ve hopefully built their app to securely support it) in order to enable it. With ASP.NET MVC 3, we are also now supporting a new attribute that you can apply to properties of models/viewmodels to indicate that HTML input is enabled, which enables much more granular protection in a DRY way.  In last month’s RC release this attribute was named [SkipRequestValidation].  With RC2 we renamed it to [AllowHtml] to make it more intuitive: Setting the above [AllowHtml] attribute on a model/viewmodel will cause ASP.NET MVC 3 to turn off HTML injection protection when model binding just that property. Html.Raw() helper method The new Razor view engine introduced with ASP.NET MVC 3 automatically HTML encodes output by default.  This helps provide an additional level of protection against HTML and Script injection attacks. With RC2 we are adding a Html.Raw() helper method that you can use to explicitly indicate that you do not want to HTML encode your output, and instead want to render the content “as-is”: ViewModel/View –> ViewBag ASP.NET MVC has (since V1) supported a ViewData[] dictionary within Controllers and Views that enables developers to pass information from a Controller to a View in a late-bound way.  This approach can be used instead of, or in combination with, a strongly-typed model class.  The below code demonstrates a common use case – where a strongly typed Product model is passed to the view in addition to two late-bound variables via the ViewData[] dictionary: With ASP.NET MVC 3 we are introducing a new API that takes advantage of the dynamic type support within .NET 4 to set/retrieve these values.  It allows you to use standard “dot” notation to specify any number of additional variables to be passed, and does not require that you create a strongly-typed class to do so.  With earlier previews of ASP.NET MVC 3 we exposed this API using a dynamic property called “ViewModel” on the Controller base class, and with a dynamic property called “View” within view templates.  A lot of people found the fact that there were two different names confusing, and several also said that using the name ViewModel was confusing in this context – since often you create strongly-typed ViewModel classes in ASP.NET MVC, and they do not use this API.  With RC2 we are exposing a dynamic property that has the same name – ViewBag – within both Controllers and Views.  It is a dynamic collection that allows you to pass additional bits of data from your controller to your view template to help generate a response.  Below is an example of how we could use it to pass a time-stamp message as well as a list of all categories to our view template: Below is an example of how our view template (which is strongly-typed to expect a Product class as its model) can use the two extra bits of information we passed in our ViewBag to generate the response.  In particular, notice how we are using the list of categories passed in the dynamic ViewBag collection to generate a dropdownlist of friendly category names to help set the CategoryID property of our Product object.  The above Controller/View combination will then generate an HTML response like below.    Output Caching Improvements ASP.NET MVC 3’s output caching system no longer requires you to specify a VaryByParam property when declaring an [OutputCache] attribute on a Controller action method.  MVC3 now automatically varies the output cached entries when you have explicit parameters on your action method – allowing you to cleanly enable output caching on actions using code like below: In addition to supporting full page output caching, ASP.NET MVC 3 also supports partial-page caching – which allows you to cache a region of output and re-use it across multiple requests or controllers.  The [OutputCache] behavior for partial-page caching was updated with RC2 so that sub-content cached entries are varied based on input parameters as opposed to the URL structure of the top-level request – which makes caching scenarios both easier and more powerful than the behavior in the previous RC. @model declaration does not add whitespace In earlier previews, the strongly-typed @model declaration at the top of a Razor view added a blank line to the rendered HTML output. This has been fixed so that the declaration does not introduce whitespace. Changed "Html.ValidationMessage" Method to Display the First Useful Error Message The behavior of the Html.ValidationMessage() helper was updated to show the first useful error message instead of simply displaying the first error. During model binding, the ModelState dictionary can be populated from multiple sources with error messages about the property, including from the model itself (if it implements IValidatableObject), from validation attributes applied to the property, and from exceptions thrown while the property is being accessed. When the Html.ValidationMessage() method displays a validation message, it now skips model-state entries that include an exception, because these are generally not intended for the end user. Instead, the method looks for the first validation message that is not associated with an exception and displays that message. If no such message is found, it defaults to a generic error message that is associated with the first exception. RemoteAttribute “Fields” -> “AdditionalFields” ASP.NET MVC 3 includes built-in remote validation support with its validation infrastructure.  This means that the client-side validation script library used by ASP.NET MVC 3 can automatically call back to controllers you expose on the server to determine whether an input element is indeed valid as the user is editing the form (allowing you to provide real-time validation updates). You can accomplish this by decorating a model/viewmodel property with a [Remote] attribute that specifies the controller/action that should be invoked to remotely validate it.  With the RC this attribute had a “Fields” property that could be used to specify additional input elements that should be sent from the client to the server to help with the validation logic.  To improve the clarity of what this property does we have renamed it to “AdditionalFields” with today’s RC2 release. ViewResult.Model and ViewResult.ViewBag Properties The ViewResult class now exposes both a “Model” and “ViewBag” property off of it.  This makes it easier to unit test Controllers that return views, and avoids you having to access the Model via the ViewResult.ViewData.Model property. Installation Notes You can download and install the ASP.NET MVC 3 RC2 build here.  It can be installed on top of the previous ASP.NET MVC 3 RC release (it should just replace the bits as part of its setup). The one component that will not be updated by the above setup (if you already have it installed) is the NuGet Package Manager.  If you already have NuGet installed, please go to the Visual Studio Extensions Manager (via the Tools –> Extensions menu option) and click on the “Updates” tab.  You should see NuGet listed there – please click the “Update” button next to it to have VS update the extension to today’s release. If you do not have NuGet installed (and did not install the ASP.NET MVC RC build), then NuGet will be installed as part of your ASP.NET MVC 3 setup, and you do not need to take any additional steps to make it work. Summary We are really close to the final ASP.NET MVC 3 release, and will deliver the final “RTM” build of it next month.  It has been only a little over 7 months since ASP.NET MVC 2 shipped, and I’m pretty amazed by the huge number of new features, improvements, and refinements that the team has been able to add with this release (Razor, Unobtrusive JavaScript, NuGet, Dependency Injection, Output Caching, and a lot, lot more).  I’ll be doing a number of blog posts over the next few weeks talking about many of them in more depth. Hope this helps, Scott P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

    Read the article

  • REST for ASP.NET MVC included in MVC 2?

    - by Mike Hodnick
    Are the REST for ASP.NET MVC bits automatically included with MVC 2, or do you need to download/install/use the REST for ASP.NET MVC bits separately? Specifically, I'm referring to the REST for ASP.NET MVC download here: http://aspnet.codeplex.com/releases/view/24471#DownloadId=79561 I want to use REST for ASP.NET MVC for the automatic json/xml serialization based on the incoming request's accepted content type. I'm not really finding any info about MVC2's ability to do this out of the "box".

    Read the article

  • asp.net mvc custom model binder

    - by mike
    pleas help guys, my custom model binder which has been working perfectly has starting giving me errors details below An item with the same key has already been added. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: An item with the same key has already been added. Source Error: Line 31: { Line 32: string key = bindingContext.ModelName; Line 33: var doc = base.BindModel(controllerContext, bindingContext) as Document; Line 34: Line 35: // DoBasicValidation(bindingContext, doc); Source File: C:\Users\Bich Vu\Documents\Visual Studio 2008\Projects\PitchPortal\PitchPortal.Web\Binders\DocumentModelBinder.cs Line: 33 Stack Trace: [ArgumentException: An item with the same key has already been added.] System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +51 System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) +7462172 System.Linq.Enumerable.ToDictionary(IEnumerable1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer1 comparer) +270 System.Linq.Enumerable.ToDictionary(IEnumerable1 source, Func2 keySelector, IEqualityComparer1 comparer) +102 System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +157 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +158 System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +90 System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +50 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1048 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +280 PitchPortal.Web.Binders.documentModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) in C:\Users\Bich Vu\Documents\Visual Studio 2008\Projects\PitchPortal\PitchPortal.Web\Binders\DocumentModelBinder.cs:33 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +257 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +109 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +314 System.Web.Mvc.Controller.ExecuteCore() +105 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +39 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7 System.Web.Mvc.<c_DisplayClass8.b_4() +34 System.Web.Mvc.Async.<c_DisplayClass1.b_0() +21 System.Web.Mvc.Async.<c_DisplayClass81.b_7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult1.End() +59 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +44 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +7 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8677678 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 any ideas guys? Thanks

    Read the article

  • asp.net mvc custom model binder

    - by mike
    pleas help guys, my custom model binder which has been working perfectly has starting giving me errors details below An item with the same key has already been added. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: An item with the same key has already been added. Source Error: Line 31: { Line 32: string key = bindingContext.ModelName; Line 33: var doc = base.BindModel(controllerContext, bindingContext) as Document; Line 34: Line 35: // DoBasicValidation(bindingContext, doc); Source File: C:\Users\Bich Vu\Documents\Visual Studio 2008\Projects\PitchPortal\PitchPortal.Web\Binders\DocumentModelBinder.cs Line: 33 Stack Trace: [ArgumentException: An item with the same key has already been added.] System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +51 System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) +7462172 System.Linq.Enumerable.ToDictionary(IEnumerable1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer1 comparer) +270 System.Linq.Enumerable.ToDictionary(IEnumerable1 source, Func2 keySelector, IEqualityComparer1 comparer) +102 System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +157 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +158 System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +90 System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +50 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1048 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +280 PitchPortal.Web.Binders.documentModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) in C:\Users\Bich Vu\Documents\Visual Studio 2008\Projects\PitchPortal\PitchPortal.Web\Binders\DocumentModelBinder.cs:33 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +257 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +109 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +314 System.Web.Mvc.Controller.ExecuteCore() +105 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +39 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7 System.Web.Mvc.<c_DisplayClass8.b_4() +34 System.Web.Mvc.Async.<c_DisplayClass1.b_0() +21 System.Web.Mvc.Async.<c__DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult1.End() +59 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +44 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +7 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8677678 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 any ideas guys? Thanks

    Read the article

  • ASP.NET MVC 3 Hosting :: Error Handling and CustomErrors in ASP.NET MVC 3 Framework

    - by C. Miller
    So, what else is new in MVC 3? MVC 3 now has a GlobalFilterCollection that is automatically populated with a HandleErrorAttribute. This default FilterAttribute brings with it a new way of handling errors in your web applications. In short, you can now handle errors inside of the MVC pipeline. What does that mean? This gives you direct programmatic control over handling your 500 errors in the same way that ASP.NET and CustomErrors give you configurable control of handling your HTTP error codes. How does that work out? Think of it as a routing table specifically for your Exceptions, it's pretty sweet! Global Filters The new Global.asax file now has a RegisterGlobalFilters method that is used to add filters to the new GlobalFilterCollection, statically located at System.Web.Mvc.GlobalFilter.Filters. By default this method adds one filter, the HandleErrorAttribute. public class MvcApplication : System.Web.HttpApplication {     public static void RegisterGlobalFilters(GlobalFilterCollection filters)     {         filters.Add(new HandleErrorAttribute());     } HandleErrorAttributes The HandleErrorAttribute is pretty simple in concept: MVC has already adjusted us to using Filter attributes for our AcceptVerbs and RequiresAuthorization, now we are going to use them for (as the name implies) error handling, and we are going to do so on a (also as the name implies) global scale. The HandleErrorAttribute has properties for ExceptionType, View, and Master. The ExceptionType allows you to specify what exception that attribute should handle. The View allows you to specify which error view (page) you want it to redirect to. Last but not least, the Master allows you to control which master page (or as Razor refers to them, Layout) you want to render with, even if that means overriding the default layout specified in the view itself. public class MvcApplication : System.Web.HttpApplication {     public static void RegisterGlobalFilters(GlobalFilterCollection filters)     {         filters.Add(new HandleErrorAttribute         {             ExceptionType = typeof(DbException),             // DbError.cshtml is a view in the Shared folder.             View = "DbError",             Order = 2         });         filters.Add(new HandleErrorAttribute());     }Error Views All of your views still work like they did in the previous version of MVC (except of course that they can now use the Razor engine). However, a view that is used to render an error can not have a specified model! This is because they already have a model, and that is System.Web.Mvc.HandleErrorInfo @model System.Web.Mvc.HandleErrorInfo           @{     ViewBag.Title = "DbError"; } <h2>A Database Error Has Occurred</h2> @if (Model != null) {     <p>@Model.Exception.GetType().Name<br />     thrown in @Model.ControllerName @Model.ActionName</p> }Errors Outside of the MVC Pipeline The HandleErrorAttribute will only handle errors that happen inside of the MVC pipeline, better known as 500 errors. Errors outside of the MVC pipeline are still handled the way they have always been with ASP.NET. You turn on custom errors, specify error codes and paths to error pages, etc. It is important to remember that these will happen for anything and everything outside of what the HandleErrorAttribute handles. Also, these will happen whenever an error is not handled with the HandleErrorAttribute from inside of the pipeline. <system.web>  <customErrors mode="On" defaultRedirect="~/error">     <error statusCode="404" redirect="~/error/notfound"></error>  </customErrors>Sample Controllers public class ExampleController : Controller {     public ActionResult Exception()     {         throw new ArgumentNullException();     }     public ActionResult Db()     {         // Inherits from DbException         throw new MyDbException();     } } public class ErrorController : Controller {     public ActionResult Index()     {         return View();     }     public ActionResult NotFound()     {         return View();     } } Putting It All Together If we have all the code above included in our MVC 3 project, here is how the following scenario's will play out: 1.       A controller action throws an Exception. You will remain on the current page and the global HandleErrorAttributes will render the Error view. 2.       A controller action throws any type of DbException. You will remain on the current page and the global HandleErrorAttributes will render the DbError view. 3.       Go to a non-existent page. You will be redirect to the Error controller's NotFound action by the CustomErrors configuration for HTTP StatusCode 404. But don't take my word for it, download the sample project and try it yourself. Three Important Lessons Learned For the most part this is all pretty straight forward, but there are a few gotcha's that you should remember to watch out for: 1) Error views have models, but they must be of type HandleErrorInfo. It is confusing at first to think that you can't control the M in an MVC page, but it's for a good reason. Errors can come from any action in any controller, and no redirect is taking place, so the view engine is just going to render an error view with the only data it has: The HandleError Info model. Do not try to set the model on your error page or pass in a different object through a controller action, it will just blow up and cause a second exception after your first exception! 2) When the HandleErrorAttribute renders a page, it does not pass through a controller or an action. The standard web.config CustomErrors literally redirect a failed request to a new page. The HandleErrorAttribute is just rendering a view, so it is not going to pass through a controller action. But that's ok! Remember, a controller's job is to get the model for a view, but an error already has a model ready to give to the view, thus there is no need to pass through a controller. That being said, the normal ASP.NET custom errors still need to route through controllers. So if you want to share an error page between the HandleErrorAttribute and your web.config redirects, you will need to create a controller action and route for it. But then when you render that error view from your action, you can only use the HandlerErrorInfo model or ViewData dictionary to populate your page. 3) The HandleErrorAttribute obeys if CustomErrors are on or off, but does not use their redirects. If you turn CustomErrors off in your web.config, the HandleErrorAttributes will stop handling errors. However, that is the only configuration these two mechanisms share. The HandleErrorAttribute will not use your defaultRedirect property, or any other errors registered with customer errors. In Summary The HandleErrorAttribute is for displaying 500 errors that were caused by exceptions inside of the MVC pipeline. The custom errors are for redirecting from error pages caused by other HTTP codes.

    Read the article

  • How to learn ASP.NET MVC without learning ASP.NET Web forms

    - by Naif
    First of all, I am not a web developer but I can say that I understand in general the difference between PHP, ASP.NET, etc. I have played a little with ASP.NET and C# as well, however, I didn't continue the learning path. Now I'd like to learn ASP.NET MVC but there is no a book for a beginner in ASP.NET MVC so I had a look at the tutorials but it seems that I need to learn C# first and SQL Server and HTML, am I right? So please tell me how can I learn ASP.NET MVC directly (I mean without learning ASP.NET Web forms). What do I need to learn (You can assume that I am an absolute beginner). Update: It is true that i can find ASP.NET MVC tutorial that explain ASP.NET MVC, but I used to find ASP.NET web forms books that explain SQL and C# at the same time and take you step by step. In ASP.NET MVC I don't know how can I start! How can I learn SQL in its own and C# in its own and then combine them with ASP.NET MVC!

    Read the article

  • What are the benefits of Castle Monorail 3 over ASP.Net MVC?

    - by yorch
    I have been using Castle Monorail for some years now with great success, although I haven't bothered to update the version I'm using (2 or 3 year old). Now I'm making a decision on go to ASP.Net MVC 3 or update to the latest Castle version. I have been looking documentation on the newest version of Castle projects (specially Monorail), but there is really little or no info around (I may be wrong). Does someone knows what are the benefits/new features of version 3 over ASP.Net MVC3? Thanks!

    Read the article

  • Course/Points to include in a educational session on Asp.net MVC 4 to be given to office colleagues

    - by bhuvin
    I am planning to take a educational session on ASP.NET MVC , now in this i am confused what all to include. Actually in office there are very less people who know about it, and are sort of closed to it. So want to take a session over it to give them a "Tip of the Iceberg". Now I want some suggestions to include into the session.And its just a 1 hour session. Dont wanna go about loading nitty gritty details. Just want to make them curious. So want some such content which amazes them. For eg : Catering same code for different devices like for mobiles.

    Read the article

  • ASP.NET MVC 3 Hosting :: Deploying ASP.NET MVC 3 web application to server where ASP.NET MVC 3 is not installed

    - by mbridge
    You can built sample application on ASP.NET MVC 3 for deploying it to your hosting first. To try it out first put it to web server where ASP.NET MVC 3 installed. In this posting I will tell you what files you need and where you can find them. Here are the files you need to upload to get application running on server where ASP.NET MVC 3 is not installed. Also you can deploying ASP.NET MVC 3 web application to server where ASP.NET MVC 3 is not installed like this example: you can change reference to System.Web.Helpers.dll to be the local one so it is copied to bin folder of your application. First file in this list is my web application dll and you don’t need it to get ASP.NET MVC 3 running. All other files are located at the following folder: C:\Program Files\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies\ If there are more files needed in some other scenarios then please leave me a comment here. And… don’t forget to convert the folder in IIS to application. While developing an application locally, this isn’t a problem. But when you are ready to deploy your application to a hosting provider, this might well be a problem if the hoster does not have the ASP.NET MVC assemblies installed in the GAC. Fortunately, ASP.NET MVC is still bin-deployable. If your hosting provider has ASP.NET 3.5 SP1 installed, then you’ll only need to include the MVC DLL. If your hosting provider is still on ASP.NET 3.5, then you’ll need to deploy all three. It turns out that it’s really easy to do so. Also, ASP.NET MVC runs in Medium Trust, so it should work with most hosting providers’ Medium Trust policies. It’s always possible that a hosting provider customizes their Medium Trust policy to be draconian. Deployment is easy when you know what to copy in archive for publishing your web site on ASP.NET MVC 3 or later versions. What I like to do is use the Publish feature of Visual Studio to publish to a local directory and then upload the files to my hosting provider. If your hosting provider supports FTP, you can often skip this intermediate step and publish directly to the FTP site. The first thing I do in preparation is to go to my MVC web application project and expand the References node in the project tree. Select the aforementioned three assemblies and in the Properties dialog, set Copy Local to True. Now just right click on your application and select Publish. This brings up the following Publish wizard Notice that in this example, I selected a local directory. When I hit Publish, all the files needed to deploy my app are available in the directory I chose, including the assemblies that were in the GAC. Another ASP.NET MVC 3 article: - New Features in ASP.NET MVC 3 - ASP.NET MVC 3 First Look

    Read the article

  • ASP.NET MVC 2 matches correct area route but generates URL to the first registered area instead.

    - by Sandor Drieënhuizen
    I'm working on a S#arpArchitecture 1.5 project, which uses ASP.NET MVC 2. I've been trying to get areas to work properly but I ran into a problem: The ASP.NET MVC 2 routing engine matches the correct route to my area but then it generates an URL that belongs to the first registered area instead. Here's my request URL: /Framework/Authentication/LogOn?ReturnUrl=%2fDefault.aspx I'm using the Route Tester from Phil Haack and it shows: Matched Route: Framework/{controller}/{action}/{id} Generated URL: /Data/Authentication/LogOn?ReturnUrl=%2FDefault.aspx using the route "Data/{controller}/{action}/{id}" That's clearly wrong, the URL should point to the Framework area, not the Data area. This is how I register my routes, nothing special there IMO. private static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); AreaRegistration.RegisterAllAreas(); routes.MapRoute( "default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }); } The area registration classes all look like this. Again, nothing special. public class FrameworkAreaRegistration : AreaRegistration { public override string AreaName { get { return "Framework"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Framework_default", "Framework/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }); } }

    Read the article

  • ASP.NET MVC 2 router matches correct area route but generates URL to the first registered area inste

    - by Sandor Drieënhuizen
    I'm working on a S#arpArchitecture 1.5 project, which uses ASP.NET MVC 2. I've been trying to get areas to work properly but I ran into a problem: The ASP.NET MVC 2 routing engine matches the correct route to my area but then it generates an URL that belongs to the first registered area instead. Here's my request URL: /Framework/Authentication/LogOn?ReturnUrl=%2fDefault.aspx I'm using the Route Tester from Phil Haack and it shows: Matched Route: Framework/{controller}/{action}/{id} Generated URL: /Data/Authentication/LogOn?ReturnUrl=%2FDefault.aspx using the route "Data/{controller}/{action}/{id}" That's clearly wrong, the URL should point to the Framework area, not the Data area. This is how I register my routes, nothing special there IMO. private static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); AreaRegistration.RegisterAllAreas(); routes.MapRoute( "default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }); } The area registration classes all look like this. Again, nothing special. public class FrameworkAreaRegistration : AreaRegistration { public override string AreaName { get { return "Framework"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Framework_default", "Framework/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }); } }

    Read the article

  • Pro ASP.NET MVC Framework Review

    - by Ben Griswold
    Early in my career, when I wanted to learn a new technology, I’d sit in the bookstore aisle and I’d work my way through each of the available books on the given subject.  Put in enough time in a bookstore and you can learn just about anything. I used to really enjoy my time in the bookstore – but times have certainly changed.  Whereas books used to be the only place I could find solutions to my problems, now they may be the very last place I look.  I have been working with the ASP.NET MVC Framework for more than a year.  I have a few projects and a couple of major deployments under my belt and I was able to get up to speed with the framework without reading a single book*.  With so many resources at our fingertips (podcasts, screencasts, blogs, stackoverflow, open source projects, www.asp.net, you name it) why bother with a book? Well, I flipped through Steven Sanderson’s Pro ASP.NET MVC Framework a few months ago. And since it is prominently displayed in my co-worker’s office, I tend to pick it up as a reference from time to time.  Last week, I’m not sure why, I decided to read it cover to cover.  Man, did I eat this book up.  Granted, a lot of what I read was review, but it was only review because I had already learned lessons by piecing the puzzle together for myself via various sources. If I were starting with ASP.NET MVC (or ASP.NET Web Deployment in general) today, the first thing I would do is buy Steven Sanderson’s Pro ASP.NET MVC Framework and read it cover to cover. Steven Sanderson did such a great job with this book! As much as I appreciated the in-depth model, view, and controller talk, I was completely impressed with all the extra bits which were included.  There a was nice overview of BDD, view engine comparisons, a chapter dedicated to security and vulnerabilities, IoC, TDD and Mocking (of course), IIS deployment options and a nice overview of what the .NET platform and C# offers.  Heck, Sanderson even include bits about webforms! The book is fantastic and I highly recommend it – even if you think you’ve already got your head around ASP.NET MVC.  By the way, procrastinators may be in luck.  ASP.NET MVC V2 Framework can be pre-ordered.  You might want to jump right into the second edition and find out what Sanderson has to say about MVC 2. * Actually, I did read through the free bits of Professional ASP.NET MVC 1.0.  But it was just a chapter – albeit a really long chapter.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >