Please post corrections/submissions to the MVC Forum. Include MVC FAQ in the title.
Post LINQ to SQL To SQL Questions here Post Entity Framework Questions here
Q: How do I get started with MVC?
MVC 2/Preview 2 Blogs:
There are three major new features in MVC 2, and several smaller ones (and bug fixes, of course).
Areas is a feature which allows segmentation and separation of your application, so that application features can be developed in isolation from one another (either in a single project or several).
Templated Input Helpers is a feature which can auto-generate forms and editors for your models, including allowing you to override templates (for example, if you always want dates edited on your site to include a drop-down Javascript calendar).
Pluggable Validation with Client-Side Validation Support allows users to get client-side validation support with jQuery Validation and DataAnnotations attributes out of the box, and supports a pluggable API to replace both client-side and server-side pieces.
You can see the ASP.NET MVC 2 Roadmap on our CodePlex site.
Stephen Walther on ASP.NET MVC
Q: Why was Default.aspx removed from MVC 2?
A: Default.aspx file should only be needed when running in IIS6 or in IIS7 Classic Mode. Neither Cassini (the built in VS web server) nor IIS7 Integrated Mode (the default) need default.aspx. The reason we took Default.aspx out is that there are many steps required to get ASP.NET MVC to work on IIS6 and IIS7 Classic Mode and having Default.aspx in the project doesn't help very much anyway since there are so many other steps.
Q: MVC is not working with GridView/ListView
A: ASP.NET MVC does not support data sources and does not support the GridView. If this is your preferred method of programming, you should use ASP.NET WebForms.
Q: MVC or Web Forms?
Q: ViewData v. tempData
http://www.squaredroot.com/2007/12/20/mvc-viewdata-vs-tempdata/ http://stackoverflow.com/questions/313572/what-is-tempdata-collection-used-for-in-asp-net-mvc http://stackoverflow.com/questions/173159/difference-between-viewdata-and-tempdata http://forums.asp.net/p/1486424/3482503.aspx
Q:How do I figure out route order?
A:Use Phil Hacck's route debugger - Also see Manually unit testing routes in ASP.Net MVC
Q: What is the correct way to write a delete action?
A: See
Q: How do I bind my model to a List?
A: See Phil's blog Model Binding To A List http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Q: My jQuery/JSON works fine on my machine, but doesn't work on the server.
A: Your URLs are not getting resolved correctly. See http://forums.asp.net/p/1486162/3484734.aspx
Q: How can I find memory leaks and profile memory usage of my MVC app?
A: Use the CLR Profiler: http://www.microsoft.com/downloads/details.aspx?FamilyId=A362781C-3870-43BE-8926-862B40AA0CD0&displaylang=en
Thomas M. has a nice blog of how to use the profiler with ASP.NET: http://blogs.msdn.com/tmarq/archive/2007/06/09/the-clr-profiler.aspx
Q: I have a view where the user fills out a form, submits and the data is displayed on a confirmation page. They must submit the confirmation page before the DB is updated (or their credit card is charged). The problem is, the confirmation page is nothing but text; so when they submit that View, nothing will be passed to the controller. The controller has no way of knowing what information the user entered 2 views ago.
A: The easiest thing to do would be to shove it into Session (if Session is enabled). Otherwise use hidden input fields or the Html.Serialize() helper from Futures. Absolutely do not use TempData for this. Hidden form fields is the right answer for scalability reasons. TempData is the wrong reason because if the user refreshes the confirmation page, then the TempData will be destroyed. Also, if Session is disabled, then the default TempData provider is also broken (since it's based on session).
Q: Is there a way to precompile MVC application including code and views for deployment?
A: You need to install the Visual Studio Web Deployment add-in (see http://www.microsoft.com/downloads/details.aspx?FamilyId=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&displaylang=en) In your MVC solution, right click on the MVC project and select "Add Web Deployment Project..." (thanks to Jacques) --- running the command line utility using aspnet_compiler will also do the job. The command line is:(framework directory)\aspnet_compiler -v /virtualDirName outputdirectoryName
Q: I'm using partial views and jQuery. When I use jQuery to do the post and updates to the page my javascript fires as I would expect. If i let Ajax.BeginForm handle it the javascript doesn't execute. Why?
A: When you update the DOM with new HTML, the browser doesn't automatically execute scripts in the new bit of HTML. MVC Ajax helpers would need to parse the partial HTML and try and execute the scripts, which is tricky and something we don't currently do.
One approach you could take is to look at jQuery live events. - source http://forums.asp.net/t/1440121.aspx
Q: How do I mix Web Forms and MVC?
A: see http://www.packtpub.com/article/mixing-asp.net-webforms-and-asp.net-mvc and http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx
Mixing ASP.NET Webforms and ASP.NET MVC http://media.wiley.com/assets/1539/15/professionalaspnet35mvc_chapter13.pdf
Free Sample Chapter — Chapter 13: Best of Both Worlds: Web Forms and MVC Together
Q: Is it possible use an enums in a controller action method?
A: Yes - See http://forums.asp.net/t/1440432.aspx
Q: What does the following do:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
A: Tells the routing engine to ignore request that end in .axd or .aspx (.aspx needed for MVC on IIS6)
Q: Invalid viewstate exception when using AntiForgeryToken error on Hosted site.
A: You can read more here: How To Fix the: “Validation of viewstate MAC failed” Error (ASP.NET MVC)
Q: Can open generic methods be used with controlers?
A: Do you mean an open generic method, such as:
public class MyController : Controller {
public ActionResult SomeAction<T>(T myParameter) { ... }
}
Or a method that is generic on a class:
public class MyController<T> : Controller {
public ActionResult SomeAction(T myParameter) { ... }
}
Example #1 is not supported in ASP.NET MVC because we don't know the type of "T". Example #2 is technically supported in MVC since by the time we get to the method we already know what the "T" is. However, the default controller factory in ASP.NET MVC cannot construct generic classes. If you have a controller factory that can create MyController<T> then ASP.NET MVC can call the action method on it.
Q: How do I use HttpContext.Cache.Add with MVC?
A: Overriding the OnActionExecuting method in the controller is the correct thing to do. The constructor of the controller is way, way too early. At that point MVC itself barely even knows what's going on. By the time the OnActionExecuting method executes you can get a lot more info about what's going on, including the ControllerContext, which is where the Cache property hangs off of.
Q:How do I parse string into javascript date object based on locale? (Globalization)
A: See http://forums.asp.net/t/1481185.aspx and http://stackoverflow.com/questions/817046/what-about-script-globalization-of-microsoftajax-js-in-asp-net-mvc (see next Q/A)
Q: How do I pass localized dates as query strings?
A: The problem with automatically parsing dates from the query string with the user's locale is that we have no idea where they came from. If the server is putting dates into URLs, it clearly can't do that using the user's locale, because then you will have non-canonical URLs (and worse, URLs which point to the wrong content depending on the user's locale). In fact, even if the date came from the user, you're still generating a non-canonical URL which the user could pass along to another user and inadvertantly send them to the wrong place.
When the values come from POSTed form fields, we know they came from the user and can then apply the user's locale when binding. - from http://forums.asp.net/t/1461209.aspx
Q:how do I generate a URL for AJAX?
A: var myUrl = '<%= Url.Action("GetDetails","Home"); %>';
$.ajax({
type: "POST",
url: myUrl });
see http://forums.asp.net/t/1461234.aspx
Q: There are 2 views in my mvc app that show a list of items. Both provide the ability to edit them by redirecting to a Edit view. How can I provide a back link on the Edit form that takes the user back to the list they were on?
A: create a hidden field in Edit view and save the UrlReferer in it. On postback use this field value to track the back address.
<%=Html.Hidden("UrlReferer",Request.Form["UrlReferer"]??Request.UrlReferer.ToString())%>
http://forums.asp.net/t/1461072.aspx
Q: How do I reference scripts?
A: <script src="<%= Url.Content("~/Public/Scripts/RunActiveContent.js") %>" type="text/javascript"></script>
CDN is the best approach: (see Microsoft Ajax CDN and the jQuery Validation Library )
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.3.2.js" type="text/javascript"></script>
Q: How do I get started on jQuery with MVC?
Q:What's the difference between temp data, view data and session data?
Q: How do I pass data on a redirect?
A: TempData - see http://blogs.teamb.com/craigstuntz/2009/01/23/37947/
Q: L2S or EF?
A:http://dotnetaddict.dotnetdevelopersjournal.com/adoef_vs_linqsql.htm
Q:Is browser still connected? if the browser is still connected before attempting to return results or doing more work?
A:There aren't very many reliable way of detecting this state. You can try to make it a bit better by writing some JavaScript that detects when the browser navigates away and sends a quick message to the server to tell it to stop the long operation. This method is unreliable, though, since if the user shuts down their browser or unplugs their computer the server won't get the message. The hard part is how does the server correlate the long-running process with the new message and know that they are the same.
Q: Why do I get the following error?
FileStream will not open Win32 devices such as disk partitions and tape drives. Avoid use of "\\.\" in the path.
A: COM1, COM2, COM3, COM4, LPT1, LPT2, CON, AUX, PRN are reserved file names, rename your view (append X) and starting with ASP.NET 4, you can rename the action back to the reserved name via:
[ActionName("con")]
public string conX() {
return "From string ActionResult conX()";
}
See http://blog.bitquabit.com/2009/06/12/zombie-operating-systems-and-aspnet-mvc/
Q: Return File does not work with non-US-ASCII
A: That is a limitation in ASP.NET MVC (file name must be US-ASCII ) and we will try to address it in an upcoming release. See more details here (and a workaround): http://forums.asp.net/t/1448041.aspx and http://forums.asp.net/t/1483316.aspx - This is documented in Controller.File Method (String, String, String) (System.Web.Mvc)
Q: why doesn't "return javascript("alert(hello);") work?
A:For the JavaScript result to work in an action method the action method must be executed via an AJAX request. In other words, you can't have a regular link tag that points at this action method. You have to create a special link using Ajax.ActionLink or using Ajax.BeginForm.
Q: How do you pass parameters using RedirectToAction?
A: You can pass parameter as GET parameters or using TempData. TempData is better solution in most cases.
http://www.augi.cz/programovani/aspnet-mvc-passing-data-when-redirecting/
http://forums.asp.net/t/1470201.aspx
Q:How do I localize Data annotations, ErrorMessageResourceName, ErrorMessageResourceType
A: See http://forums.asp.net/t/1433699.aspx
Q: How do I replace the error message ""A value is required" with my own custom error message?
A: See http://stackoverflow.com/questions/646270/asp-net-mvc-custom-validation-message-for-value-types/1374653#1374653
Q: How do I move sessionID from the default (cookie) to the querystring?
A: See http://forums.asp.net/t/1480365.aspx
Q: How do I keep track of wrong answers on a form submit (limited guesses on security question)?
A: See http://forums.asp.net/p/1476843/3460584.aspx
Q:I'm setting the value of a hidden with tempData, but the value is always overridden on postback. What's the problem?
A: On postback, all input helpers -- including hidden -- render the value that's in ModelState rather than the value that's provided from ViewData or the helper method. The assumption is that if you're re-rendering the form on postback, then it's because there was an error, and we should show the values the user typed rather than the values in the object. See http://forums.asp.net/p/1476843/3460584.aspx
In your controller action, you could remove the hidden value from ModelState to force it to use the new value.
Q: I want to pre populate some of the form fields from browser cookies. How to set and load cookies in an mvc app?
A: The same way as in any ASP.NET application - via Cookies property on Request and Response objects. These objects are accessible from controller via HttpContext.Request and HttpContext.Response properties. So just use HttpContext.Request.Cookies and HttpContext.Response.Cookies from your controller. See http://forums.asp.net/t/1482840.aspx
Q: XHTML header indentation format is not respected for some tags - why?
A: In the default MVC template the <head> tag in the Site.master file (in the ~/Views/Shared folder) is marked as runat="server". This special attribute gives the tag additional behavior that in some cases is nice, and in other cases it can cause formatting problems. You can remove the runat="server" attribute from the <head> tag but that can cause certain URLs to map incorrectly. The following will not work
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
You’ll have to call Url.Content() instead, like we do for javaScript files. The only thing you lose at that point is Design View in VS (it’ll work but you won’t see the CSS styles). see http://forums.asp.net/t/1482073.aspx
Q: How do I prevent Invalid viewstate exception when using AntiForgeryToken?
A: See http://forums.asp.net/t/1479165.aspx
Q: How do I create Cascading Drop Down boxes in MVC?
A: http://stackoverflow.com/questions/705540/asp-net-mvc-cascading-drop-down
Q: Authorize filter and what it exactly does.
A: See http://forums.asp.net/t/1382315.aspx
Q: How do I create a custom role provider for MVC?
A: See http://forums.asp.net/t/1382315.aspx
Q: How do I keep track of posts to security questions (wrong answer) to limit a client to N guesses?
S: See http://forums.asp.net/p/1476843/3438217.aspx
A: Routing links - see http://forums.asp.net/t/1476922.aspx
Q: How do I enable MVC on IIS5.1 (XP) or IIS 6?
Q: How do I use JSON in MVC?
A: See http://weblogs.asp.net/mehfuzh/archive/2009/04/28/using-of-json-result-in-asp-net-mvc-1-0.aspx
Q: I have an Ajax.ActionLink that loads a partial view into a div, using a get method. The problem is, the user can just visit controller/AjaxAction directly, like they could with any action method. Basically, I need an ActionMethod that accepts HttpVerbs.Get, but can only be called by Ajax; as opposed to being called as a normal action.
A: check if Request.IsAjaxRequest() is true or false. If it is false, you could redirect somewhere else for example. If it is true, then continue processing.You could even create a custom action filter that checks this and makes the decision.
Q: In WebForms, I use Page.Request.ServerVariables["LOGON_USER"]; to get the current logged in user. How do I do this in MVC?
A: Have the controller put it in ViewData. (thanks paul.vencill )
ViewData["username"] = User.Identity.Name;
Q: How do I prevent a user from sending us confidential data (credit card number, SSN, etc.) over an unsecured channel (HTTP)?
A: You can't. If the user sends confidential data via HTTP you can't go back in time and undo the transmission. Action methods that handle posts of confidential data should use the [RequireHttps] Attribute; the action method will ignore the post and force the sender to use HTTPS.
Q: Will the [RequireHttps] Attribute prevent Man in the Middle Attacks (MITM) or DNS cache poisoning attacks?
A: The [RequireHttps] Attribute can't prevent MITM or DNS cache poisoning attacks, but HTTPS in general does protect against these.
Q: Why do I get the following build error: The "xxx" task failed unexpectedly. System.UnauthorizedAccessException: Access to the path 'C:\Path...' is denied.
A: You're probably hitting a known bug related to source control systems which leave your source files as read-only by default (like TFS). The first copy succeeds because there isn't anything there, but the second copy fails because it refuses to overwrite the read-only copies of the files from the first time around. There is no work-around today besides checking out all the files that will be copied so that they're read-write instead of read-only.
Q: How do I use MVC with LiveID ?
A: Write your own Authorize filter. See http://forums.asp.net/t/1487782.aspx
Q: How do I fix the following error: "A potentially dangerous Request.Form value was detected from the client "
A: See http://forums.asp.net/t/1487699.aspx
Q: MVC App rendering in IE ok, but not in Firefox, Chrome, and Safari
A: The Site.Master page's DOCTYPE was set to STRICT. I changed it to Transitional, and now the pages render the same in all browsers. See http://forums.asp.net/p/1484722/3489894.aspx
Q: How do I check which event caused a post back?
A: See http://forums.asp.net/t/1488333.aspx
Q: How does MVC get indexed from search engines if the URL's are not file base?
A: See http://forums.asp.net/t/1490362.aspx
Q: How do I display data from my master page?
A: You can use RenderAction from inside of a MasterPage. Just make an action and associated partial view for whatever it is you want to render in the Master Page. see http://forums.asp.net/t/1490283.aspx