I am using vs2010 win7 x64 MVC 3 with regular asp.net development server. And the newest versions of firefox, IE9 and chrome.
I have a strongly typed view and i'm trying to get a ajax extention method working via a slightly modified version of this code asp-net-mvc-ajax-actionlink-with-image that Arjan Einbu provided for mvc 3.
Here is my extension method code located in a Helper.cs file in the App_Code folder of my mvc website.
public static class HelperExtensions
{
public static IHtmlString ImageActionLink(this AjaxHelper helper, string imageUrl, string titleText, string actionName, object routeValues, AjaxOptions ajaxOptions)
{
var builder = new TagBuilder("img");
builder.MergeAttribute("src", imageUrl);
builder.MergeAttribute("title", titleText);
var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions).ToHtmlString();
return new MvcHtmlString(link.Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing)));
}
}
In my view I have #model IEnumerable<Models.SpeciesType> at the top defining the model and I'm using ...
#Ajax.ImageActionLink(Url.Content("~/Content/ThumbUp.png"), "Valid/Appropriate", "VoteUp", new {id = item.ID}, new AjaxOptions { HttpMethod = "POST" } );
to insert the ajax action link with an image to allow the user to vote on the item. The above code does not work and no matter what I do it keep giving me error after endless error. The current error it is giving me is ...
Compiler Error Message: CS0121: The
call is ambiguous between the
following methods or properties:
'HelperExtensions.ImageActionLink(System.Web.Mvc.AjaxHelper,
string, string, string, object,
System.Web.Mvc.Ajax.AjaxOptions)' and
'HelperExtensions.ImageActionLink(System.Web.Mvc.AjaxHelper,
string, string, string, object,
System.Web.Mvc.Ajax.AjaxOptions)'
Which means I have two methods with the same name and signature in the same namespace that are conflicting, again impossible because I have only defined it once in one code file. So I thought there might me a caching issue so I did a ctrl+shift+delete in firefox and did a full clear of the cache, history and everything else. Refreshed the page and I get the same error. I also tested it in IE9 and chrome same issue.
I stopped and started the asp.net development server, quit visual studio and restarted still same issue.
Did disk clean up checked everything and ran it. Disk Cleanup did not delete all the files in "C:\Users\Dean\AppData\Local\Temp" So I manually deleted all remaining files in the folder that i could in including the "Temporary ASP.NET Files" folder. Then I ran vs2010 again and ran the website. Again still the same error "CS0121: The call is ambiguous between the following methods ... etc etc"
I can't get rid of this error no matter what I do. This was not the only error I was getting. Before this error started persisting I was also getting errors relating to mvc not being able to find a ImageActionLink method with the right signature namely
ImageActionLink(this AjaxHelper<IEnumerable<SpeciesType>> helper, etc etc
that error I assume was relating to the fact that I am using a strongly typed view.
So to try and get rid of the "call is ambiguous" error I commented out the entire ImageActionLink method and recompiled and ran the website again. I got this error
Compiler Error Message: CS1061:
'System.Web.Mvc.AjaxHelper>'
does not contain a definition for
'ImageActionLink' and no extension
method 'ImageActionLink' accepting a
first argument of type
'System.Web.Mvc.AjaxHelper>'
could be found (are you missing a
using directive or an assembly
reference?)
That error totally makes sense because the ImageActionLink no longer exists. So next thing I did was un-comment the ImageActionLink method recompile and run the website again. And sure enough the same "call is ambiguous" error.
I'm at a loss. I've done everything I can think of to clear various cache's to rule that out, comment and un-comment out pieces of code and test what part breaks. But I'm stuck not being able to get passed the "call is ambiguous" error.
Anyone have any ideas how to fix this "call is ambiguous" error so I can get on to asking why I can't seem to get a simple ajax extension method working ?
I got rid of the "call is ambiguous" error. What happened was I copied Arjan Einbu's mvc 3 version of the code found here asp-net-mvc-ajax-actionlink-with-image.
Then I created a new class in visual studio in the App_Code folder and did a ctrl+a ctrl+v and replaced all the pre generated class template code with just the HelperExtensions class. The problem was that I did not wrap the HelperExtensions with a namespace that matched the website namespace.
Something about how asp.net compiles code files without namespaces was screwing it up. I'm asuming it's probably because the code is compiled in the main website dll at build time and then when asp.net runs it compiles any code files it finds in the app_code folder thus two classes with the same name and same method name or some such.
Anyway now that I have solved that aggravation, I run my website and I get the fallowing error ...
Compiler Error Message: CS1061: 'System.Web.Mvc.AjaxHelper<IEnumerable<Models.SpeciesType>>' does not contain a definition for 'ImageActionLink' and no extension method 'ImageActionLink' accepting a first argument of type 'System.Web.Mvc.AjaxHelper<IEnumerable<Models.SpeciesType>>' could be found (are you missing a using directive or an assembly reference?)
The error reads as though it's finding the ImageActionLink method but the first parameter on the ImageActionLink method is not of the type AjaxHelper<IEnumerable<Models.SpeciesType>>
The error does not quite make sense. Yes the first parameter on the ImageActionLink method is of type AjaxHelper but not of the generic AjaxHelper type. So I tried to modify the ImageActionLink method declaration like so
public static IHtmlString ImageActionLink(this AjaxHelper<IEnumerable<SpeciesType>> helper, string imageUrl, string titleText, string actionName, object routeValues, AjaxOptions ajaxOptions)
But I still get the same error. The first parameter on ImageActionLink is of type AjaxHelper but it's defined "this AjaxHelper helper" meaning it's a extension method that is supposed to extend the AjaxHelper class.
I don't really need the #model IEnumerable<Models.SpeciesType> at the top of my index.cshtml file so I removed it and tried to run the app again with the same error only this time it's
Compiler Error Message: CS1061: 'System.Web.Mvc.AjaxHelper<dynamic>' does not contain a definition for 'ImageActionLink' and no extension method 'ImageActionLink' accepting a first argument of type 'System.Web.Mvc.AjaxHelper<dynamic>' could be found (are you missing a using directive or an assembly reference?)
Anyone know why I'm getting this error? And how to fix it?
Where in Web.config have you added namespace (you are using razor views) ? To pages or to
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="toolbox" />
<add namespace="aa.App_Code"/>
</namespaces>
</pages>
</system.web.webPages.razor>
try adding here, modify view (add some tag), and check if it works.
Related
I'm getting an exception on a Xamarin Forms content page with Xaml, on the initializecomponent method. The exception occurs on the generated xaml.gs page. I haven't changed any code form a working version. Maybe something upstream has changed. The exception message is ""
Value cannot be null.
Parameter name: binding
stack trace:
at Xamarin.Forms.BindableObject.SetBinding (Xamarin.Forms.BindableProperty targetProperty, Xamarin.Forms.BindingBase binding, System.Boolean fromStyle) [0x00011] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:293
at Xamarin.Forms.BindableObject.SetBinding (Xamarin.Forms.BindableProperty targetProperty, Xamarin.Forms.BindingBase binding) [0x00000] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:117
at ....LoginPage.InitializeComponent () [0x00045] in ...\obj\Debug\netstandard2.0\Views\Navigation\Login.xaml.g.cs:34
at FieldServices.LoginPage..ctor () [0x0002b] in ..\Views\Navigation\Login.xaml.cs:25
where occurrs:
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
private void InitializeComponent() {
global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(LoginPage));
email = global::Xamarin.Forms.NameScopeExtensions.FindByName(this, "email");
password = global::Xamarin.Forms.NameScopeExtensions.FindByName(this, "password");
loginButton = global::Xamarin.Forms.NameScopeExtensions.FindByName(this, "loginButton");
}
I rarely get this error when pulling code down. First, double-check that your code is fine. In this case, I would make sure all the bindings are named correctly with no typos.
In the event that you cannot find an error and are thoroughly convinced there is nothing wrong with the code, try steps like
Clean and Rebuild
Close your Visual Studio and restart it
Hopefully the error is solved as easy as this.
On top of cleaning and rebuilding, manually delete all the obj and bin folders from your solution directory. Those xaml.gs files are generated files and sometimes they seem to not regenerate when they should.
I'm getting an exception on a Xamarin Forms content page with Xaml, on the initializecomponent method. The exception occurs on the generated xaml.gs page. I haven't changed any code form a working version. Maybe something upstream has changed.
It is not reproduceable by myside, but per experience there are a few things you can try:
Put your project in a short path like "C:\".
Try a new blank project, see if the error occors.
If none of the above works, you can try reinstalling Xamarin in your VS.
This was solved due to my not linking a static resource that was declared in the xaml
This project used to work. I fuddled with the connection string in Web.Config trying to get it to work with .accdb file. Forget that.
But now I can't get back home to a working project.
HomeController.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using oesac.Models;
namespace oesac.Controllers
{
[HandleError]
public class HomeController : Controller
{
oesacEntities_connection _db;
public HomeController()
{
_db = new oesacEntities_connection();
}
=============================
E:\oesac_MVC\Controllers\HomeController.cs(52,42): error CS1061: 'oesac.Models.oesacEntities_connection' does not contain a definition for 'Courses' and no extension method 'Courses' accepting a first argument of type 'oesac.Models.oesacEntities_connection' could be found (are you missing a using directive or an assembly reference?)
(_db.Courses is underlined, just Courses has the underline)
//SEARCH BY COURSE TITLE
var courses = (from m in _db.Courses select m);
=======================
The Entity Container Name is:
"oesacEntities_connection"
It has 2 tables, Courses and Sponsors, and refreshes tables when I right click in .edmx window and select "Update Model From Database".
So database is there and VS 2010 sees it.
But for some reason there is a disconnect in referencing all this.
If I breeze through the popup after the errors that says "would you like to continue" I get a webpage with this error:
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Could not load type 'oesac.MvcApplication'.
Source Error:
Line 1: <%# Application Codebehind="Global.asax.cs" Inherits="oesac.MvcApplication" Language="C#" %>
And this is what is in Global.asax.cs:
namespace oesac
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
I'm thinking if it was snake it would have bit me. But a little too new at this MVC dreamworld.
Ok, if someone else understands this better I can give them the green checkmark for correct answer. However, a friend at work said sometimes with EF you just have to wipe the slate clean and add a new Entity Framework class. And not get too clever. I had changed the names of the tables in VS 2010 .edmx file like it says you can and somehow the Gremlins took over.
Friend at work and 2 other people came to realize this after pulling out all their hair on one of there first major MVC projects.
And, yes, I did try all the mumbo jumbo of "Update Model From Database" right click in the .edmx in VS.
How can I view the request body in ASP.NET Web API from Visual Studio? In ASP.NET MVC, you can use QuickWatch to inspect the Request object and view the content of the body and any posted form data. From what I read, ASP.NET Web API doesn't allow you to read the body more than once.
This is very annoying to deal with when trying to figure out why a specific value wasn't bound correctly. Is there a quick way to do this without setting up tracing/logging?
The easiest it to install Fiddler. Then you will see everything that gets sent over the wire and inspect not only the request payload but the HTTP headers as well. And if you are consuming the API from javascript, things like FireBug, Chrome Developer Toolbar and IE Developer Tools will show you all network requests made by the website.
If you absolutely must inspect the traffic on the server then if you are hosting your Web API inside an ASP.NET application you could put the following line in your immediate window:
new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd()
if you need body >> Form-data
Post localhost:53356/api/carparksapi/GetRecod
key=jsonRequest and value=[{"abcd":"zxxx"}]
// API -Controller Method ::
var httpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
var foo = httpContext.Request.Form["jsonRequest"];
return foo; //This is value passed in request
For ASP.NET Core use this in the immediate window:
new System.IO.StreamReader(Request.Body).ReadToEnd()
For me #DarinDimitrov answer gave
error CS0246: The type or namespace name 'StreamReader' could not be found (are you missing a using directive or an assembly reference?)
Adding namespace did it
new System.IO.StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd()
Hope this saves you some time
For me #Matas Vaitkevicius answer gave
error CS1061: 'HttpContextBase' does not contain a definition for
'Current' and no extension method 'Current' accepting a first argument
of type 'HttpContextBase' could be found (are you missing a using
directive or an assembly reference?)
Replacing HttpContext.Current with System.Web.HttpContext.Current did it for me
new System.IO.StreamReader(System.Web.HttpContext.Current.Request.InputStream).ReadToEnd()
Hope this saves you some time
Any of these answers could work if the position of the steam is at position 0.
HttpContext.Current.Request.InputStream.Position = 0;
var body = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
I created a new MVC3 project, hit F5, saw the sample page.
Then I used NuGet to get the Ninject.MVC extension. I modified my global.asax according to the Ninject documentation, How To Setup an MVC3 Application:
public class MvcApplication : NinjectHttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index",
id = UrlParameter.Optional });
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
Now when I run the app, I get the yellow screen of death with the following exception:
InvalidOperationException - Sequence contains no elements.
at System.Linq.Enumerable.Single(...)
at Ninject.Web.Mvc.Bootstrapper.Initialize(...)
line 67.
And sure enough, line 67 of that file calls .Single(), thus throwing the exception.
What am I doing wrong?
I have to add to this in the hopes that someone else will resolve the issue more quickly and not want to pull out every strand of hair on their head like I almost did.
I needed to rename everything in my project to match new business terms. I changed namespaces everywhere and I even changed the Assembly Name (right-click project > properties > application tab) so that the generated assembly matches the new naming convention. The assembly rename is what made Ninject very angry!
By renaming the assembly that gets generated a new file with the new name was being created when we compiled. However, the old file with the old name was still in the bin directory! If you have Ninject activating via the added class in App_Start then this activation class will get invoked in BOTH assemblies (old one AND new renamed one). Don't ask me how or why, but it does and it gives you this "already initialized" error.
Not even cleaning solution works because Visual Studio will only remove the binaries that it is generating, which would be the new renamed ones. It leaves the old ones alone just sitting there.
Go delete your bin folder before you try doing anything else! I hope this saves someone else from wasting valuable working hours!
You might notice that after installing the ninject.mvc3 NuGet there is an App_Start subfolder created inside your project containing an NinjectMVC3.cs file. Delete this folder and try again. So here are the steps I followed:
Create a new ASP.NET MVC 3 project using the default template
Bring up the Package Manager Console window (View -> Other Windows -> Package Manager Console)
Type install-package ninject.mvc3 on the command line
Replace the default code in Global.asax with the code in your question
Delete the AppStart subfolder created during the installation of the package
Run the application
Enjoy the beauty of the /Home/Index default page opened in your Google Chrome web browser :-)
I have updated the documentation Wiki linked in your question to show both ways to setup a MVC3 application. I suggest to use the second option which is the prefered way for theNuGetpackage.
Instead of deriving from NinjectHttpApplication it is using the NinjectMVC.cs in the AppStart folder which is created during installation of the package. This is also the location where you create the kernel and where you load your modules or where you define the bindings.
As Alex Ford said:
I have to add to this in the hopes that someone else will resolve the
issue more quickly and not want to pull out every strand of hair on
their head like I almost did.
I had a special version of that problem which could get solved as follows:
Exception Details: System.InvalidOperationException: Sequence contains no elements
This error is caused by the fact that there are 2 projects with
App_Start/NinjectWebCommon.cs
Removing the file eliminates the error.
Note: if you are nu-getting Ninject.Web.Common because you need to
reference Ninject.Web.Common assembly for one of your class library
project, you can safely remove the “App_Start” folder and
“NinjectWebCommon.cs”. It is meant for web/web api projects.
>click here to view the original blog entry<
My solution was that I had set the App_Start folder property, Namespace Provider to True.
I had changed this to False so that Resharper wouldn't highlight the namespace NOT matching the folder structure.
Wanted to add one more cause ...
We installed the Ninject.MVC3 package to multiple projects - only one of which was an actual MVC applicaiton. However, we forgot to remove the App_Start folder.
Removing the App_Start folder from the referenced project resolved the issue.
To tack on to #Chev's answer... this was my ultimate issue as well. If you're deploying to an Azure Website (now named AppSite), you want to click on this box in the publish to remove old files
I have a web app based on MVC3 (no beta or release candidate, RTM/RTW version) that has an action that accepts XML files for processing.
Of course, this seems evil to MVC because of possible attacks, so it doesn't allow it. Well, I try to put either AllowHtml on the model object as such:
public class XMLModel
{
[AllowHtml]
public string msg { get; set; }
}
Or I set ValidateInput to false on my action method such as this:
[ValidateInput(false)]
public ActionResult AddCDR(XMLModel model)
{
}
The reason for having a "strongly" typed model in the first place was that I originally tried to have a string value named "msg" as the action method parameter, but that always came back empty.
Now, when someone posts to this form, either on the same machine or from a networked computer, the msg field is always blank.
I have verified with WireShark that the data is actually in the request.
Now, one interesting thing. This should not be necessary with MVC 3. Yet it makes a slight difference.
If I add this to my web config:
<httpRuntime requestValidationMode="2.0" />
It works for requests originating from the local computer, but it does NOT work from another system.
I think the AllowHtml version seems elegant - if only it worked.
I have also found out about a bug in RC2 - again, this should not affect me, but I tried to add the following in Application_Start() anyway:
ModelMetadataProviders.Current = new DataAnnotationsModelMetadataProvider();
As expected, it makes no real difference.
Everything works as expected on my development computer (Win7x64, VS2010), but on the target system (Win2008R2x64, IIS7.5) the above problems are giving me a hard time.
Very important point to note: If I post to the action with no angle brackets, I get the form data as expected. As soon as the angle brackets show up, though, either my action isn't called at all, or it doesn't find the form data, neither in action method parameters or in for instance Request.Params["msg"] where it should be.
Any ideas to allow the XML through?
UPDATE
I've tried to work my way around this while waiting for anyone to come up with an answer here. I have not been able to solve it yet, but I have checked a few additional details;
First, I verified that the ASP.NET MVC 3 version installed on both my development computer and on the web server is the same; v3.0.20105.0 (according to Add/Remove programs).
The web application was actually created with the MVC3 beta, then converted to RC1 and RC2 as they came out, and finally to the RTM version. This meant I had to modify some code because of the ViewBag change. However, since I didn't know exactly what else had changed, I created a brand new MVC3 application with the RTM version, created a controller by the same name, with the same action method, taking a model object similar to the currently used one, renamed the old web app directory and put this new one in place. Exactly the same thing happens - i.e. the parameter with the AllowHtml attribute comes through with all content when the request is made from the local machine, but if it comes from a remote machine, then the HTML (XML actually) is stripped out.
There is no exception. I've installed Elmah and verified this - no exception occurs, my action method is apparently just called with anything looking like XML stripped out from the parameters to the method.
Needless to say, this is driving me crazy. I had some advice yesterday to look at the source code of MVC3, but unfortunately that doesn't really help me, as I can't see anything obviously wrong there, and I can't debug code on the server in question.
Any insights still highly desired, thanks! :)
I cannot reproduce this.
Model:
using System.Web.Mvc;
namespace MvcApplication3.Models {
public class XmlModel {
[AllowHtml]
public string msg { get; set; }
}
}
Controller:
using System.Web.Mvc;
using MvcApplication3.Models;
namespace MvcApplication3.Controllers {
public class HomeController : Controller {
public ActionResult Index() {
return View();
}
[HttpPost]
public ActionResult Index(XmlModel model) {
return View();
}
}
}
View:
#model MvcApplication3.Models.XmlModel
#using (Html.BeginForm()) {
<div class="editor-label">
#Html.LabelFor(model => model.msg)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.msg)
#Html.ValidationMessageFor(model => model.msg)
</div>
}
These were added to a default empty MVC 3 project. Everything posts fine. When I remove [AllowHtml], it generates the appropriate error message.
I am answering this myself because this was an obscure situation, and MVC3 was not the problem.
The system that POSTed data to my application was doing so with malformed data. In addition to that, I was told that they were also POSTing to an older MVC2 application that worked just fine - this was wrong, it turned out they were GETting in that case, and GET they happen to do correctly.
If anything, fairly thorough testing has confirmed that the AllowHtml attribute actually works very well. Never trust your input, tho. :)