Search Results

Search found 25175 results on 1007 pages for 'classic asp'.

Page 15/1007 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • asp.net mvc outputting json with backslashes ( escape) despite many attemps to filter

    - by minus4
    i have an asp.net controller that output Json as the results a section of it is here returnString += string.Format(@"{{""filename"":""{0}"",""line"":[", file.Filename); what i get returned is this: "{\"DPI\":\"66.8213457076566\",\"width\":\"563.341067\",\"editable\":\"True\",\"pricecat\":\"6\",\"numpages\":\"2\",\"height\":\"400\",\"page\":[{\"filename\":\"999_9_1.jpg\",\"line\":[]},{\"filename\":\"999_9_2.jpg\",\"line\":[]}]]" i have tried to return with the following methods: return Json(returnString); return Json(returnString.Replace("\\",""); return Json will serialize my string to a jSon string, this i know but it likes to escape for some reason, how can i get rid of it ???? for info this is how i call it with jQuery: $.ajax({ url:"/Products/LoadArtworkToJSon", type:"POST", dataType: "json", async: false, data:{prodid: prodid }, success: function(data){ sessvars.myData = data; measurements = sessvars.myData; $("#loading").remove(); //empty the canvas and create a new one with correct data, always start on page 0; $("#movements").remove(); $("#canvas").append("<div id=\"movements\" style=\"width:" + measurements.width + "px; height:" + Math.round(measurements.height) + "px; display:block; border:1px solid black; background:url(/Content/products/" + measurements.page[0].filename + ") no-repeat;\"></div>"); your help is much appreciated thanks

    Read the article

  • Asp.net MVC VirtualPathProvider views parse error

    - by madcapnmckay
    Hi, I am working on a plugin system for Asp.net MVC 2. I have a dll containing controllers and views as embedded resources. I scan the plugin dlls for controller using StructureMap and I then can pull them out and instantiate them when requested. This works fine. I then have a VirtualPathProvider which I adapted from this post public class AssemblyResourceProvider : VirtualPathProvider { protected virtual string WidgetDirectory { get { return "~/bin"; } } private bool IsAppResourcePath(string virtualPath) { var checkPath = VirtualPathUtility.ToAppRelative(virtualPath); return checkPath.StartsWith(WidgetDirectory, StringComparison.InvariantCultureIgnoreCase); } public override bool FileExists(string virtualPath) { return (IsAppResourcePath(virtualPath) || base.FileExists(virtualPath)); } public override VirtualFile GetFile(string virtualPath) { return IsAppResourcePath(virtualPath) ? new AssemblyResourceVirtualFile(virtualPath) : base.GetFile(virtualPath); } public override CacheDependency GetCacheDependency(string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart) { return IsAppResourcePath(virtualPath) ? null : base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart); } } internal class AssemblyResourceVirtualFile : VirtualFile { private readonly string path; public AssemblyResourceVirtualFile(string virtualPath) : base(virtualPath) { path = VirtualPathUtility.ToAppRelative(virtualPath); } public override Stream Open() { var parts = path.Split('/'); var resourceName = Path.GetFileName(path); var apath = HttpContext.Current.Server.MapPath(Path.GetDirectoryName(path)); var assembly = Assembly.LoadFile(apath); return assembly != null ? assembly.GetManifestResourceStream(assembly.GetManifestResourceNames().SingleOrDefault(s => string.Compare(s, resourceName, true) == 0)) : null; } } The VPP seems to be working fine also. The view is found and is pulled out into a stream. I then receive a parse error Could not load type 'System.Web.Mvc.ViewUserControl<dynamic>'. which I can't find mentioned in any previous example of pluggable views. Why would my view not compile at this stage? Thanks for any help, Ian EDIT: Getting closer to an answer but not quite clear why things aren't compiling. Based on the comments I checked the versions and everything is in V2, I believe dynamic was brought in at V2 so this is fine. I don't even have V3 installed so it can't be that. I have however got the view to render, if I remove the <dynamic> altogether. So a VPP works but only if the view is not strongly typed or dynamic This makes sense for the strongly typed scenario as the type is in the dynamically loaded dll so the viewengine will not be aware of it, even though the dll is in the bin. Is there a way to load types at app start? Considering having a go with MEF instead of my bespoke Structuremap solution. What do you think?

    Read the article

  • ASP.NET MVC 2 "value" in IsValid override in DataAnnotation attribute passed is null, when incorrect

    - by goldenelf2
    Hello to all! This is my first question here on stack overflow. i need help on a problem i encountered during an ASP.NET MVC2 project i am currently working on. I should note that I'm relatively new to MVC design, so pls bear my ignorance. Here goes : I have a regular form on which various details about a person are shown. One of them is "Date of Birth". My view is like this <div class="form-items"> <%: Html.Label("DateOfBirth", "Date of Birth:") %> <%: Html.EditorFor(m => m.DateOfBirth) %> <%: Html.ValidationMessageFor(m => m.DateOfBirth) %> </div> I'm using an editor template i found, to show only the date correctly : <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>"%> <%= Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty))%> I used LinqToSql designer to create my model from an sql database. In order to do some validation i made a partial class Person to extend the one created by the designer (under the same namespace) : [MetadataType(typeof(IPerson))] public partial class Person : IPerson { //To create buddy class } public interface IPerson { [Required(ErrorMessage="Please enter a name")] string Name { get; set; } [Required(ErrorMessage="Please enter a surname")] string Surname { get; set; } [Birthday] DateTime? DateOfBirth { get; set; } [Email(ErrorMessage="Please enter a valid email")] string Email { get; set; } } I want to make sure that a correct date is entered. So i created a custom DataAnnotation attribute in order to validate the date : public class BirthdayAttribute : ValidationAttribute { private const string _errorMessage = "Please enter a valid date"; public BirthdayAttribute() : base(_errorMessage) { } public override bool IsValid(object value) { if (value == null) { return true; } DateTime temp; bool result = DateTime.TryParse(value.ToString(), out temp); return result; } } Well, my problem is this. Once i enter an incorrect date in the DateOfBirth field then no custom message is displayed even if use the attribute like [Birthday(ErrorMessage=".....")]. The message displayed is the one returned from the db ie "The value '32/4/1967' is not valid for DateOfBirth.". I tried to enter some break points around the code, and found out that the "value" in attribute is always null when the date is incorrect, but always gets a value if the date is in correct format. The same ( value == null) is passed also in the code generated by the designer. This thing is driving me nuts. Please can anyone help me deal with this? Also if someone can tell me where exactly is the point of entry from the view to the database. Is it related to the model binder? because i wanted to check exactly what value is passed once i press the "submit" button. Thank you.

    Read the article

  • Creating STA COM compatible ASP.NET Applications

    - by Rick Strahl
    When building ASP.NET applications that interface with old school COM objects like those created with VB6 or Visual FoxPro (MTDLL), it's extremely important that the threads that are serving requests use Single Threaded Apartment Threading. STA is a COM built-in technology that allows essentially single threaded components to operate reliably in a multi-threaded environment. STA's guarantee that COM objects instantiated on a specific thread stay on that specific thread and any access to a COM object from another thread automatically marshals that thread to the STA thread. The end effect is that you can have multiple threads, but a COM object instance lives on a fixed never changing thread. ASP.NET by default uses MTA (multi-threaded apartment) threads which are truly free spinning threads that pay no heed to COM object marshaling. This is vastly more efficient than STA threading which has a bit of overhead in determining whether it's OK to run code on a given thread or whether some sort of thread/COM marshaling needs to occur. MTA COM components can be very efficient, but STA COM components in a multi-threaded environment always tend to have a fair amount of overhead. It's amazing how much COM Interop I still see today so while it seems really old school to be talking about this topic, it's actually quite apropos for me as I have many customers using legacy COM systems that need to interface with other .NET applications. In this post I'm consolidating some of the hacks I've used to integrate with various ASP.NET technologies when using STA COM Components. STA in ASP.NET Support for STA threading in the ASP.NET framework is fairly limited. Specifically only the original ASP.NET WebForms technology supports STA threading directly via its STA Page Handler implementation or what you might know as ASPCOMPAT mode. For WebForms running STA components is as easy as specifying the ASPCOMPAT attribute in the @Page tag:<%@ Page Language="C#" AspCompat="true" %> which runs the page in STA mode. Removing it runs in MTA mode. Simple. Unfortunately all other ASP.NET technologies built on top of the core ASP.NET engine do not support STA natively. So if you want to use STA COM components in MVC or with class ASMX Web Services, there's no automatic way like the ASPCOMPAT keyword available. So what happens when you run an STA COM component in an MTA application? In low volume environments - nothing much will happen. The COM objects will appear to work just fine as there are no simultaneous thread interactions and the COM component will happily run on a single thread or multiple single threads one at a time. So for testing running components in MTA environments may appear to work just fine. However as load increases and threads get re-used by ASP.NET COM objects will end up getting created on multiple different threads. This can result in crashes or hangs, or data corruption in the STA components which store their state in thread local storage on the STA thread. If threads overlap this global store can easily get corrupted which in turn causes problems. STA ensures that any COM object instance loaded always stays on the same thread it was instantiated on. What about COM+? COM+ is supposed to address the problem of STA in MTA applications by providing an abstraction with it's own thread pool manager for COM objects. It steps in to the COM instantiation pipeline and hands out COM instances from its own internally maintained STA Thread pool. This guarantees that the COM instantiation threads are STA threads if using STA components. COM+ works, but in my experience the technology is very, very slow for STA components. It adds a ton of overhead and reduces COM performance noticably in load tests in IIS. COM+ can make sense in some situations but for Web apps with STA components it falls short. In addition there's also the need to ensure that COM+ is set up and configured on the target machine and the fact that components have to be registered in COM+. COM+ also keeps components up at all times, so if a component needs to be replaced the COM+ package needs to be unloaded (same is true for IIS hosted components but it's more common to manage that). COM+ is an option for well established components, but native STA support tends to provide better performance and more consistent usability, IMHO. STA for non supporting ASP.NET Technologies As mentioned above only WebForms supports STA natively. However, by utilizing the WebForms ASP.NET Page handler internally it's actually possible to trick various other ASP.NET technologies and let them work with STA components. This is ugly but I've used each of these in various applications and I've had minimal problems making them work with FoxPro STA COM components which is about as dififcult as it gets for COM Interop in .NET. In this post I summarize several STA workarounds that enable you to use STA threading with these ASP.NET Technologies: ASMX Web Services ASP.NET MVC WCF Web Services ASP.NET Web API ASMX Web Services I start with classic ASP.NET ASMX Web Services because it's the easiest mechanism that allows for STA modification. It also clearly demonstrates how the WebForms STA Page Handler is the key technology to enable the various other solutions to create STA components. Essentially the way this works is to override the WebForms Page class and hijack it's init functionality for processing requests. Here's what this looks like for Web Services:namespace FoxProAspNet { public class WebServiceStaHandler : System.Web.UI.Page, IHttpAsyncHandler { protected override void OnInit(EventArgs e) { IHttpHandler handler = new WebServiceHandlerFactory().GetHandler( this.Context, this.Context.Request.HttpMethod, this.Context.Request.FilePath, this.Context.Request.PhysicalPath); handler.ProcessRequest(this.Context); this.Context.ApplicationInstance.CompleteRequest(); } public IAsyncResult BeginProcessRequest( HttpContext context, AsyncCallback cb, object extraData) { return this.AspCompatBeginProcessRequest(context, cb, extraData); } public void EndProcessRequest(IAsyncResult result) { this.AspCompatEndProcessRequest(result); } } public class AspCompatWebServiceStaHandlerWithSessionState : WebServiceStaHandler, IRequiresSessionState { } } This class overrides the ASP.NET WebForms Page class which has a little known AspCompatBeginProcessRequest() and AspCompatEndProcessRequest() method that is responsible for providing the WebForms ASPCOMPAT functionality. These methods handle routing requests to STA threads. Note there are two classes - one that includes session state and one that does not. If you plan on using ASP.NET Session state use the latter class, otherwise stick to the former. This maps to the EnableSessionState page setting in WebForms. This class simply hooks into this functionality by overriding the BeginProcessRequest and EndProcessRequest methods and always forcing it into the AspCompat methods. The way this works is that BeginProcessRequest() fires first to set up the threads and starts intializing the handler. As part of that process the OnInit() method is fired which is now already running on an STA thread. The code then creates an instance of the actual WebService handler factory and calls its ProcessRequest method to start executing which generates the Web Service result. Immediately after ProcessRequest the request is stopped with Application.CompletRequest() which ensures that the rest of the Page handler logic doesn't fire. This means that even though the fairly heavy Page class is overridden here, it doesn't end up executing any of its internal processing which makes this code fairly efficient. In a nutshell, we're highjacking the Page HttpHandler and forcing it to process the WebService process handler in the context of the AspCompat handler behavior. Hooking up the Handler Because the above is an HttpHandler implementation you need to hook up the custom handler and replace the standard ASMX handler. To do this you need to modify the web.config file (here for IIS 7 and IIS Express): <configuration> <system.webServer> <handlers> <remove name="WebServiceHandlerFactory-Integrated-4.0" /> <add name="Asmx STA Web Service Handler" path="*.asmx" verb="*" type="FoxProAspNet.WebServiceStaHandler" precondition="integrated"/> </handlers> </system.webServer> </configuration> (Note: The name for the WebServiceHandlerFactory-Integrated-4.0 might be slightly different depending on your server version. Check the IIS Handler configuration in the IIS Management Console for the exact name or simply remove the handler from the list there which will propagate to your web.config). For IIS 5 & 6 (Windows XP/2003) or the Visual Studio Web Server use:<configuration> <system.web> <httpHandlers> <remove path="*.asmx" verb="*" /> <add path="*.asmx" verb="*" type="FoxProAspNet.WebServiceStaHandler" /> </httpHandlers> </system.web></configuration> To test, create a new ASMX Web Service and create a method like this: [WebService(Namespace = "http://foxaspnet.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class FoxWebService : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World. Threading mode is: " + System.Threading.Thread.CurrentThread.GetApartmentState(); } } Run this before you put in the web.config configuration changes and you should get: Hello World. Threading mode is: MTA Then put the handler mapping into Web.config and you should see: Hello World. Threading mode is: STA And you're on your way to using STA COM components. It's a hack but it works well! I've used this with several high volume Web Service installations with various customers and it's been fast and reliable. ASP.NET MVC ASP.NET MVC has quickly become the most popular ASP.NET technology, replacing WebForms for creating HTML output. MVC is more complex to get started with, but once you understand the basic structure of how requests flow through the MVC pipeline it's easy to use and amazingly flexible in manipulating HTML requests. In addition, MVC has great support for non-HTML output sources like JSON and XML, making it an excellent choice for AJAX requests without any additional tools. Unlike WebForms ASP.NET MVC doesn't support STA threads natively and so some trickery is needed to make it work with STA threads as well. MVC gets its handler implementation through custom route handlers using ASP.NET's built in routing semantics. To work in an STA handler requires working in the Page Handler as part of the Route Handler implementation. As with the Web Service handler the first step is to create a custom HttpHandler that can instantiate an MVC request pipeline properly:public class MvcStaThreadHttpAsyncHandler : Page, IHttpAsyncHandler, IRequiresSessionState { private RequestContext _requestContext; public MvcStaThreadHttpAsyncHandler(RequestContext requestContext) { if (requestContext == null) throw new ArgumentNullException("requestContext"); _requestContext = requestContext; } public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { return this.AspCompatBeginProcessRequest(context, cb, extraData); } protected override void OnInit(EventArgs e) { var controllerName = _requestContext.RouteData.GetRequiredString("controller"); var controllerFactory = ControllerBuilder.Current.GetControllerFactory(); var controller = controllerFactory.CreateController(_requestContext, controllerName); if (controller == null) throw new InvalidOperationException("Could not find controller: " + controllerName); try { controller.Execute(_requestContext); } finally { controllerFactory.ReleaseController(controller); } this.Context.ApplicationInstance.CompleteRequest(); } public void EndProcessRequest(IAsyncResult result) { this.AspCompatEndProcessRequest(result); } public override void ProcessRequest(HttpContext httpContext) { throw new NotSupportedException("STAThreadRouteHandler does not support ProcessRequest called (only BeginProcessRequest)"); } } This handler code figures out which controller to load and then executes the controller. MVC internally provides the information needed to route to the appropriate method and pass the right parameters. Like the Web Service handler the logic occurs in the OnInit() and performs all the processing in that part of the request. Next, we need a RouteHandler that can actually pick up this handler. Unlike the Web Service handler where we simply registered the handler, MVC requires a RouteHandler to pick up the handler. RouteHandlers look at the URL's path and based on that decide on what handler to invoke. The route handler is pretty simple - all it does is load our custom handler: public class MvcStaThreadRouteHandler : IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { if (requestContext == null) throw new ArgumentNullException("requestContext"); return new MvcStaThreadHttpAsyncHandler(requestContext); } } At this point you can instantiate this route handler and force STA requests to MVC by specifying a route. The following sets up the ASP.NET Default Route:Route mvcRoute = new Route("{controller}/{action}/{id}", new RouteValueDictionary( new { controller = "Home", action = "Index", id = UrlParameter.Optional }), new MvcStaThreadRouteHandler()); RouteTable.Routes.Add(mvcRoute);   To make this code a little easier to work with and mimic the behavior of the routes.MapRoute() functionality extension method that MVC provides, here is an extension method for MapMvcStaRoute(): public static class RouteCollectionExtensions { public static void MapMvcStaRoute(this RouteCollection routeTable, string name, string url, object defaults = null) { Route mvcRoute = new Route(url, new RouteValueDictionary(defaults), new MvcStaThreadRouteHandler()); RouteTable.Routes.Add(mvcRoute); } } With this the syntax to add  route becomes a little easier and matches the MapRoute() method:RouteTable.Routes.MapMvcStaRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); The nice thing about this route handler, STA Handler and extension method is that it's fully self contained. You can put all three into a single class file and stick it into your Web app, and then simply call MapMvcStaRoute() and it just works. Easy! To see whether this works create an MVC controller like this: public class ThreadTestController : Controller { public string ThreadingMode() { return Thread.CurrentThread.GetApartmentState().ToString(); } } Try this test both with only the MapRoute() hookup in the RouteConfiguration in which case you should get MTA as the value. Then change the MapRoute() call to MapMvcStaRoute() leaving all the parameters the same and re-run the request. You now should see STA as the result. You're on your way using STA COM components reliably in ASP.NET MVC. WCF Web Services running through IIS WCF Web Services provide a more robust and wider range of services for Web Services. You can use WCF over HTTP, TCP, and Pipes, and WCF services support WS* secure services. There are many features in WCF that go way beyond what ASMX can do. But it's also a bit more complex than ASMX. As a basic rule if you need to serve straight SOAP Services over HTTP I 'd recommend sticking with the simpler ASMX services especially if COM is involved. If you need WS* support or want to serve data over non-HTTP protocols then WCF makes more sense. WCF is not my forte but I found a solution from Scott Seely on his blog that describes the progress and that seems to work well. I'm copying his code below so this STA information is all in one place and quickly explain. Scott's code basically works by creating a custom OperationBehavior which can be specified via an [STAOperation] attribute on every method. Using his attribute you end up with a class (or Interface if you separate the contract and class) that looks like this: [ServiceContract] public class WcfService { [OperationContract] public string HelloWorldMta() { return Thread.CurrentThread.GetApartmentState().ToString(); } // Make sure you use this custom STAOperationBehavior // attribute to force STA operation of service methods [STAOperationBehavior] [OperationContract] public string HelloWorldSta() { return Thread.CurrentThread.GetApartmentState().ToString(); } } Pretty straight forward. The latter method returns STA while the former returns MTA. To make STA work every method needs to be marked up. The implementation consists of the attribute and OperationInvoker implementation. Here are the two classes required to make this work from Scott's post:public class STAOperationBehaviorAttribute : Attribute, IOperationBehavior { public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.ClientOperation clientOperation) { // If this is applied on the client, well, it just doesn’t make sense. // Don’t throw in case this attribute was applied on the contract // instead of the implementation. } public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation) { // Change the IOperationInvoker for this operation. dispatchOperation.Invoker = new STAOperationInvoker(dispatchOperation.Invoker); } public void Validate(OperationDescription operationDescription) { if (operationDescription.SyncMethod == null) { throw new InvalidOperationException("The STAOperationBehaviorAttribute " + "only works for synchronous method invocations."); } } } public class STAOperationInvoker : IOperationInvoker { IOperationInvoker _innerInvoker; public STAOperationInvoker(IOperationInvoker invoker) { _innerInvoker = invoker; } public object[] AllocateInputs() { return _innerInvoker.AllocateInputs(); } public object Invoke(object instance, object[] inputs, out object[] outputs) { // Create a new, STA thread object[] staOutputs = null; object retval = null; Thread thread = new Thread( delegate() { retval = _innerInvoker.Invoke(instance, inputs, out staOutputs); }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); outputs = staOutputs; return retval; } public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state) { // We don’t handle async… throw new NotImplementedException(); } public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result) { // We don’t handle async… throw new NotImplementedException(); } public bool IsSynchronous { get { return true; } } } The key in this setup is the Invoker and the Invoke method which creates a new thread and then fires the request on this new thread. Because this approach creates a new thread for every request it's not super efficient. There's a bunch of overhead involved in creating the thread and throwing it away after each thread, but it'll work for low volume requests and insure each thread runs in STA mode. If better performance is required it would be useful to create a custom thread manager that can pool a number of STA threads and hand off threads as needed rather than creating new threads on every request. If your Web Service needs are simple and you need only to serve standard SOAP 1.x requests, I would recommend sticking with ASMX services. It's easier to set up and work with and for STA component use it'll be significantly better performing since ASP.NET manages the STA thread pool for you rather than firing new threads for each request. One nice thing about Scotts code is though that it works in any WCF environment including self hosting. It has no dependency on ASP.NET or WebForms for that matter. STA - If you must STA components are a  pain in the ass and thankfully there isn't too much stuff out there anymore that requires it. But when you need it and you need to access STA functionality from .NET at least there are a few options available to make it happen. Each of these solutions is a bit hacky, but they work - I've used all of them in production with good results with FoxPro components. I hope compiling all of these in one place here makes it STA consumption a little bit easier. I feel your pain :-) Resources Download STA Handler Code Examples Scott Seely's original STA WCF OperationBehavior Article© Rick Strahl, West Wind Technologies, 2005-2012Posted in FoxPro   ASP.NET  .NET  COM   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

  • Execute TSQL statement with ExecuteStoreQuery in entity framework 4.0

    - by Jalpesh P. Vadgama
    I was playing with entity framework in recent days and I was searching something that how we can execute TSQL statement in entity framework. And I have found one great way to do that with entity framework ‘ExecuteStoreQuery’ method. It’s executes a TSQL statement against data source given enity framework context and returns strongly typed result. You can find more information about ExcuteStoreQuery from following link. http://msdn.microsoft.com/en-us/library/dd487208.aspx So let’s examine how it works. So Let’s first create a table against which we are going to execute TSQL statement. So I have added a SQL Express database as following. Now once we are done with adding a database let’s add a table called Client like following. Here you can see above Client table is very simple. There are only two fields ClientId and ClientName where ClientId is primary key and ClientName is field where we are going to store client name. Now it’s time to add some data to the table. So I have added some test data like following. Now it’s time to add entity framework model class. So right click project->Add new item and select ADO.NET entity model as following. After clicking on add button a wizard will start it will ask whether we need to create model classes from database or not but we already have our client table ready so I have selected generate from database as following. Once you process further in wizard it will be presented a screen where we can select the our table like following. Now once you click finish it will create model classes with for us. Now we need a gridview control where we need to display those data. So in Default.aspx page I have added a grid control like following. <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="EntityFramework._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> Welcome to ASP.NET! </h2> <p> To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>. </p> <p> You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409" title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>. <asp:GridView ID="grdClient" runat="server"> </asp:GridView> </p> </asp:Content> Now once we are done with adding Gridview its time to write code for server side. So I have written following code in Page_load event of default.aspx page. protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { using (var context = new EntityFramework.TestEntities()) { ObjectResult<Client> result = context.ExecuteStoreQuery<Client>("Select * from Client"); grdClient.DataSource = result; grdClient.DataBind(); } } } Here in the above code you can see that I have written create a object of our entity model and then with the help of the ExecuteStoreQuery method I have execute a simple select TSQL statement which will return a object result. I have bind that object result with gridview to display data. So now we are done with coding.So let’s run application in browser. Following is output as expected. That’s it. Hope you like it. Stay tuned for more..Till then happy programming.

    Read the article

  • PathTooLongException after migrating from ASP.NET MVC 1 to ASP.NET MVC 2

    - by admax
    I had updated my app from MVC 1 to MVC 2. After that some pages throws PathTooLongException: [PathTooLongException: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.] System.IO.Path.SafeSetStackPointerValue(Char* buffer, Int32 index, Char value) +7493057 System.IO.Path.NormalizePathFast(String path, Boolean fullCheck) +387 System.IO.Path.NormalizePath(String path, Boolean fullCheck) +36 System.IO.Path.GetFullPathInternal(String path) +21 System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath) +73 System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath) +278 System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList) +87 System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String path) +65 System.Web.InternalSecurityPermissions.PathDiscovery(String path) +29 System.Web.HttpRequest.MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, Boolean allowCrossAppMapping) +146 System.Web.HttpRequest.MapPath(VirtualPath virtualPath) +37 System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +43 System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +28 System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +22 System.Web.Mvc.ViewPage.RenderView(ViewContext viewContext) +284 System.Web.Mvc.WebFormView.RenderViewPage(ViewContext context, ViewPage page) +82 System.Web.Mvc.WebFormView.Render(ViewContext viewContext, TextWriter writer) +85 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +267 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +10 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +320 System.Web.Mvc.Controller.ExecuteCore() +104 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +36 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() +53 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +30 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +7 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8678910 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 I know the issue with 260-character-url-lenght in ASP.NET, but my app works fine before update to ASP.NET MVC 2.0!

    Read the article

  • Asp.Net membership via ASP.NET Website Administrator Tool

    - by luppi
    I created a database with aspnet_regsql, the database was created in sql sever 2008 and not in data folder in my project (do I need to move it to the folder manually?). Next, in Web Site Administration Tool I went to provider section and clicked don Test button. I got an error: Could not establish a connection to the database. If you have not yet created the SQL Server database, exit the Web Site Administration tool, use the aspnet_regsql command-line utility to create and configure the database, and then return to this tool to set the provider. Maybe I need to set something in a web.config, like membership settings or connection strings (or ASP.NET Website Administrator Tool should create those settings for me)? Update: Maybe it happens because I am using SQL server 2008 full and not express? Update 2: After setting membership section and connection string to my aspnetdb database in Web Site Administration Tool I've opened security-Security Setup Wizard-Define Roles (stage 4) I got this error: An error was encountered. Please return to the previous page and try again. The following message may help in diagnosing the problem: Unable to connect to SQL Server database. at System.Web.Administration.WebAdminPage.CallWebAdminHelperMethod(Boolean isMembership, String methodName, Object[] parameters, Type[] paramTypes) at ASP.security_wizard_wizardpermission_ascx.OnInit(EventArgs e) at System.Web.UI.Control.InitRecursive(Control namingContainer) at System.Web.UI.Control.InitRecursive(Control namingContainer) at System.Web.UI.Control.InitRecursive(Control namingContainer) at System.Web.UI.Control.InitRecursive(Control namingContainer) at System.Web.UI.Control.InitRecursive(Control namingContainer) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

    Read the article

  • ASP.net AppendHeader not working in ASP MVC

    - by Chao
    I'm having problems getting AppendHeader to work properly if I am also using an authorize filter. I'm using an actionfilter for my AJAX actions that applies Expires, Last-Modified, Cache-Control and Pragma (though while testing I have tried including it in the action method itself with no change in results). If I don't have an authorize filter the headers work fine. Once I add the filter the headers I tried to add get stripped. The headers I want to add Response.AppendHeader("Expires", "Sun, 19 Nov 1978 05:00:00 GMT"); Response.AppendHeader("Last-Modified", String.Format("{0:r}", DateTime.Now)); Response.AppendHeader("Cache-Control", "no-store, no-cache, must-revalidate"); Response.AppendHeader("Cache-Control", "post-check=0, pre-check=0"); Response.AppendHeader("Pragma", "no-cache"); An example of the headers from a correct page: Server ASP.NET Development Server/9.0.0.0 Date Mon, 14 Jun 2010 17:22:24 GMT X-AspNet-Version 2.0.50727 X-AspNetMvc-Version 2.0 Pragma no-cache Expires Sun, 19 Nov 1978 05:00:00 GMT Last-Modified Mon, 14 Jun 2010 18:22:24 GMT Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Content-Type text/html; charset=utf-8 Content-Length 352 Connection Close And from an incorrect page: Server ASP.NET Development Server/9.0.0.0 Date Mon, 14 Jun 2010 17:27:34 GMT X-AspNet-Version 2.0.50727 X-AspNetMvc-Version 2.0 Pragma no-cache, no-cache Cache-Control private, s-maxage=0 Content-Type text/html; charset=utf-8 Content-Length 4937 Connection Close

    Read the article

  • Leaving Microsoft

    - by Stephen Walther
    After two and a half years working with the ASP.NET team, I’ve decided that this is the right time to leave Microsoft and, with the help of some friends, re-launch my ASP.NET training and consulting company. The company has the modest name Superexpert. While working on my Ph.D. at MIT, I was surrounded by professors and students who were passionate about knowledge. During the Internet boom, I was lucky enough to work side-by-side with some very smart and hard-working people to create several successful startups. However, the people I worked with at Microsoft were among the smartest and hardest working. Microsoft hires a small number of people and gives them huge responsibilities. It continues to amaze me that so few people work on the ASP.NET team when you consider how much the team produces. I had the opportunity to work with a number of inspiring people at Microsoft. I’ll miss working with Scott Hunter, Dave Reed, Boris Moore, Eilon Lipton, Scott Guthrie, James Senior, Jim Wang, Phil Haack, Damian Edwards, Vishal Joshi, Mike Pope, Jon Young, Dmitry Robsman, Simon Calvert, Stefan Schackow, and many others. I’m proud of what we accomplished while I was working at Microsoft. We reached out to the jQuery team and changed direction from Microsoft Ajax to jQuery. We successfully contributed several important new features to the open-source jQuery project including jQuery Templates, jQuery Data-Linking, jQuery Globalization, and (as John Resig announced at the last jQuery conference) jQuery Require. I’m looking forward to returning to training and consulting. We want to focus on providing consulting on the “right way” of building ASP.NET websites, which we call Modern ASP.NET applications. By Modern ASP.NET applications, I mean applications built with ASP.NET MVC, jQuery, HTML5, and Visual Studio ALM. Additionally, we want to help companies that have existing ASP.NET Web Forms applications migrate to ASP.NET MVC. If you are interested in having us provide training for your company or you need help building a custom ASP.NET application then please contact us at [email protected] or visit our website at Superexpert.com.

    Read the article

  • Does 'Web Pages' use the same syntax as 'MVC'?

    - by Laberto
    I see that there is a new model in ASP.NET development which called 'ASP.NET Web Pages'. I would like to know if this model resembles the ASP.NET MVC Model. The point is that I found it difficult to learn ASP.NET MVC and someone told me: OK, if you learn ASP.NET Web Pages at first then learning ASP.NET MVC will be easier because of the Razor syntax in both models. Could you please tell me the truth if you have tried both?

    Read the article

  • Guest (and occasional co-host) on Jesse Liberty's Yet Another Podcast

    - by Jon Galloway
    I was a recent guest on Jesse Liberty's Yet Another Podcast talking about the latest Visual Studio, ASP.NET and Azure releases. Download / Listen: Yet Another Podcast #75–Jon Galloway on ASP.NET/ MVC/ Azure Co-hosted shows: Jesse's been inviting me to co-host shows and I told him I'd show up when I was available. It's a nice change to be a drive-by co-host on a show (compared with the work that goes into organizing / editing / typing show notes for Herding Code shows). My main focus is on Herding Code, but it's nice to pop in and talk to Jesse's excellent guests when it works out. Some shows I've co-hosted over the past year: Yet Another Podcast #76–Glenn Block on Node.js & Technology in China Yet Another Podcast  #73 - Adam Kinney on developing for Windows 8 with HTML5 Yet Another Podcast #64 - John Papa & Javascript Yet Another Podcast #60 - Steve Sanderson and John Papa on Knockout.js Yet Another Podcast #54–Damian Edwards on ASP.NET Yet Another Podcast #53–Scott Hanselman on Blogging Yet Another Podcast #52–Peter Torr on Windows Phone Multitasking Yet Another Podcast #51–Shawn Wildermuth: //build, Xaml Programming & Beyond And some more on the way that haven't been released yet. Some of these I'm pretty quiet, on others I get wacky and hassle the guests because, hey, not my podcast so not my problem. Show notes from the ASP.NET / MVC / Azure show: What was just released Visual Studio 2012 Web Developer features ASP.NET 4.5 Web Forms Strongly Typed data controls Data access via command methods Similar Binding syntax to ASP.NET MVC Some context: Damian Edwards and WebFormsMVP Two questions from Jesse: Q: Are you making this harder or more complicated for Web Forms developers? Short answer: Nothing's removed, it's just a new option History of SqlDataSource, ObjectDataSource Q: If I'm using some MVC patterns, why not just move to MVC? Short answer: This works really well in hybrid applications, doesn't require a rewrite Allows sharing models, validation, other code between Web Forms and MVC ASP.NET MVC Adaptive Rendering (oh, also, this is in Web Forms 4.5 as well) Display Modes Mobile project template using jQuery Mobile OAuth login to allow Twitter, Google, Facebook, etc. login Jon (and friends') MVC 4 book on the way: Professional ASP.NET MVC 4 Windows 8 development Jesse and Jon announce they're working on a new book: Pro Windows 8 Development with XAML and C# Jon and Jesse agree that it's nice to be able to write Windows 8 applications using the same skills they picked up for Silverlight, WPF, and Windows Phone development. Compare / contrast ASP.NET MVC and Windows 8 development Q: Does ASP.NET and HTML5 development overlap? Jon thinks they overlap in the MVC world because you're writing HTML views without controls Jon describes how his web development career moved from a preoccupation with server code to a focus on user interaction, which occurs in the browser Jon mentions his NDC Oslo presentation on Learning To Love HTML as Beautiful Code Q: How do you apply C# / XAML or HTML5 skills to Windows 8 development? Q: If I'm a XAML programmer, what's the learning curve on getting up to speed on ASP.NET MVC? Jon describes the difference in application lifecycle and state management Jon says it's nice that web development is really interactive compared to application development Q: Can you learn MVC by reading a book? Or is it a lot bigger than that? What is Azure, and why would I use it? Jon describes the traditional Azure platform mode and how Azure Web Sites fits in Q: Why wouldn't Jesse host his blog on Azure Web Sites? Domain names on Azure Web Sites File hosting options Q: Is Azure just another host? How is it different from any of the other shared hosting options? A: Azure gives you the ability to scale up or down whenever you want A: Other services are available if or when you want them

    Read the article

  • IIS7 Session ID rotating with Classic ASP

    - by ManiacZX
    I am trying to migrate a Classic ASP app onto a Windows 2008 R2 server. The application features run fine, but I am having issue with session. The application keeps the logged in user information in session and I am constantly getting knocked out as if the session had expired. While debugging I have discovered the sessions are not expiring but instead I am getting 2-3 different Session IDs in use by one browser. I am outputting Response.Write(Session.SessionID) on various pages in the application and I can sit there and hit refresh over and over and watch the number changed between these 2-3 SessionIDs randomly. The sessions are still valid because when I refresh and get the Session ID that I logged in under the page is displayed (because the security check was successful) and when I get one of the other Session IDs I get the "you aren't logged in, you need to log in" message. If I close and re-open the browser, same story just the set of IDs are new. This happens with IE8, Firefox and Chrome from multiple computers. Things I've tried: - AppPool set to No Managed Code and Classic - Output Caching set .asp to never cache - ASP Session Properties enabled and disabled asp session state and confirmed it affected page (error trying to read Session.SessionID when disabled) Things I've tried just in case but shouldn't have anything to do with ASP Session: - Disabled compression - Changed ASP.Net Session State properties (InProc, StateServer, SQLServer, Cookies, URI, etc) -

    Read the article

  • Windows 7 / IIS 7 / Classic ASP not working

    - by Lucenut
    I have some old classic asp scripts. They used to work on my 2003/IIS 6 server. But on my Vista/IIS 7 and now Windows 7 Ultimate/IIS 7 server the asp pages don't work. I did what they said here: Deploying a Classic ASP Server (IIS 7) (Microsoft TechNet). I enabled those 3 features in IIS 7 but that just went from getting 404 to 500 error.

    Read the article

  • ASP.NET MVC Html.RouteLink

    - by gilbertc
    I am trying to understand what this RouteLink does. Say, in my Global.asax, I have the default route for MVC routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); and on a View page, I do <%=Html.RouteLink("Dinners", "Default", new { controller="Dinners", action="Details", id="1"} %> Why it does not generate the link /Dinners/Details/1 but thrown an exception? Thanks. Gil.

    Read the article

  • Ajax comments form in ASP.NET MVC2

    - by Artiom Chilaru
    I've been playing around with different aspects of MVC for some time now, and I've reached a situation where I'm not sure what would be the best way to solve a problem. I'm hoping that the SO community will help me out here :P I've seen a number of examples of Ajax.BeginForm on the internet, and it seems like a very nifty idea. E.g. you have a dropdown where you select a customer - and on selecting one it will load this client's details in some placeholder on the page. This works perfectly fine. But what to do if you want to tie in some validation in the box? Just hypothetically, imagine an article page, and user comments in the bottom. Below the comments area there's an ajax-y "Add comment" box. When a user adds a comment, it will appear in the comments area, below the last comment there. If I set the Ajax.BeginForm to Append the result of the call to the Comments area, it will work fine. But what if the data posted is not valid? Instead of appending a "successful" comment to the comments area I have to show the user validation errors. At this point I decided that the area INSIDE the Ajax.BeginForm will be inside a partial, and the form's submits will return this partial. Validation works fine. On each submit we reload the contents inside the form element. But how to add the successful comment to the top? Other things to consider: The comment form also has a "Preview" button. When the user clicks on Preview, I should load the rendered comment into a preview box. This will probably be inside the form area as well. I was thinking of using Json results instead. When the user submits the form, the server code will generate a Json object with a Success value, and html rendered partials as some properties. Something like { "success": true, "form": "<html form data>", "comment": "successful comment html to inject into the page" } This would be a perfect solution, except there's no way in MVC to render a partial into a string, inside the controller (separation of context, remember?). So.. what should I do then? Any "correct" way to implement this?

    Read the article

  • ASP.NET MVC Routing - Redirect to aspx?

    - by bmoeskau
    This seems like it should be easy, but for some reason I'm having no luck. I'm migrating an existing WebForms app to MVC, so I need to keep the root of the site pointing to my existing aspx pages for now and only apply routing to named routes. Here's what I have: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{resource}.aspx/{*pathInfo}"); RouteTable.Routes.Add( "Root", new Route("", new DefaultRouteHandler()) ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Calendar2", action = "Index", id = "" } // Parameter defaults ); } So aspx pages should be ignored, and the default root url should be handled by this handler: public class DefaultRouteHandler : IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { return System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath( "~/Dashboard/default.aspx", typeof(Page)) as IHttpHandler; } } This seems to work OK, but the resulting YPOD gives me this: Multiple controls with the same ID '__Page' were found. Trace requires that controls have unique IDs. which seems to imply that the page is somehow getting rendered twice. If I simply type in the url to my dashboard page directly it works fine (no routing, no error). I have no idea why the handler code would be doing anything differently. Bottom line -- I'd like to simply redirect the root url path to an aspx of my choosing -- can anyone shed some light?

    Read the article

  • ASP.NET MVC 2 - Html.DropDownList not working in an AJAX form

    - by Jacob
    I am trying to create an MVC 2 solution and I have run into the following problem: Index.aspx: <% using(Ajax.BeginForm("Forms", new AjaxOptions{UpdateTargetId="form", HttpMethod="POST"})) { %> <h3>Input: </h3> <p><%= Html.DropDownList("dropDown")%> <input type="submit" value="Select Mission" /></p> <% } %> HomeController.cs: public ActionResult Index() { var list = new [] { "item1", "item2", "item3" }; ViewData["dropDown"] = new SelectList(list); return View(); } public ActionResult Forms(string dropDown) { if (dropDown == null || dropDown == "") ViewData["txt"] = "Ahhh..."; else ViewData["txt"] = "You entered: " + dropDown; return PartialView("Form", dropDown); } Form.ascx: <%: ViewData["txt"] % This does not work. However, the whole thing does work if I use an Html.TextBox instead. For example: <div id="form"> <% using(Ajax.BeginForm("Forms", new AjaxOptions{UpdateTargetId="form", HttpMethod="POST"})) { %> <h3>Input: </h3> <%= Html.TextBox("textBox") %> <input type="submit" value="Select Mission" /></p> <% } %> </div> (and refactor the method in the controller so that it's argument is textBox instead of dropDown). My question is why does the AJAX form work for an Html.TextBox, but not for an Html.DropDownList, or what am I doing wrong? My only idea is that maybe the argument in the controller is not supposed to be of type string when using a DropDownList, but this is really just a guess. Thanks in advance.

    Read the article

  • Creating .NET 3.0 sub-applications within .NET 1.1 applications in IIS/ASP.Net

    - by Karen
    I am basically trying to do the same thing as this question, create a new application within a folder so it could be accessed as follows. * http://www.domain.com/ < Main App * http://www.domain.com/newapp < New App The problem is that newapp is reading the web.config from the Main App, which is causing errors because it doesn't have all the same dlls etc. For New App, in IIS, the starting point is set at /newapp, so I am not sure why it is reading the web.config from / at all. It is set as it's own application. I am testing this in IIS6 on XP Pro, so not sure if that makes a difference. The Main App is dotnet 1.1, and New App is 3.0. Edit: Adding 'inheritInChildApplications to <location doesn't work in 1.1, you get an error: Parser Error Message: Unrecognized attribute 'inheritInChildApplications'

    Read the article

  • help me with asp.net mvc 2 custom validation attribute

    - by Omu
    I'm trying to write a validation attribute that is going to check that at least one of the specified properties is true [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class AtLeastOneTrueAttribute : ValidationAttribute { private const string DefaultErrorMessage = "select at least one"; public AtLeastOneTrueAttribute(params string[] props) : base(DefaultErrorMessage) { this.props = props; } private readonly string[] props; public override string FormatErrorMessage(string name) { return DefaultErrorMessage; } public override bool IsValid(object value) { var properties = TypeDescriptor.GetProperties(value); return props.Any(p => (bool) properties.Find(p, true).GetValue(value)); } } now when I'm trying to use I can't really get specify the props after the fir , the intellisence shows me that I'm entering the ErrorMessage and only the first string is the params string[] props

    Read the article

  • Altering the ASP.NET MVC 2 ActionResult on HTTP post

    - by Inge Henriksen
    I want to do some processing on a attribute before returning the view. If I set the appModel.Markup returned in the HttpPost ActionResult method below to "modified" it still says "original" on the form. Why cant I modify my attribute in a HttpGet ActionResult method? [HttpGet] public ActionResult Index() { return View(new MyModel { Markup = "original" }); } [HttpPost] public ActionResult Index(MyModel appModel) { return View(new MyModel { Markup = "modified" }); }

    Read the article

  • Asp.net mvc json

    - by user310657
    Hi, I am working on a mvc project, and having problem with json. i have created a demo project with list of colors public JsonResult GetResult() { List strList = new List(); strList.Add("white"); strList.Add("blue"); strList.Add("black"); strList.Add("red"); strList.Add("orange"); strList.Add("green"); return this.Json(strList); } i am able to get these on my page, but when i try to delete one color, that is when i send the following using jquery function deleteItem(item) { $.ajax({ type: "POST", url: "/Home/Delete/white", data: "{}", contentType: "application/json; charset=utf-8", success: ajaxCallSucceed, dataType: "json", failure: ajaxCallFailed }); } the controler action public JsonResult Delete(string Color) {} Color always returns null, even if i have specified "/Home/Delete/white" in the url. i know i am doing something wrong or missing something, but not able to find out what. please can any one guide me in the right direction.

    Read the article

  • Asp.net: Replace GenericPrincipal

    - by Pickels
    Hello, I was wondering what the best way is to replace the genericPrincipal with my own CustomGenericPrincipal. At the moment I have something like this but I aint sure if it's correct. protected void Application_AuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); var identity = new CustomIdentity(authTicket); var principal = new CustomPrincipal(identity); Context.User = principal; } else { //Todo: check if this is correct var genericIdentity = new CustomGenericIdentity(); Context.User = new CustomPrincipal(genericIdentity); } } I need to replace it because I need a Principal that implements my ICustomPrincipal interface because I am doing the following with Ninject: Bind<ICustomPrincipal>().ToMethod(x => (ICustomPrincipal)HttpContext.Current.User) .InRequestScope(); So what's the best way to replace the GenericPrincipal? Thanks in advance, Pickels

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >