CS1003 Error in Razor View - asp.net-mvc-3

The following line generates a CS1003 error in ASP.NET MVC 3:
#model Int32 // user ID
What is the cause of this error?

The CS1003 error is a general symptom of a failure by MVC to parse the Razor syntax. It could be caused by many things.
One thing I've noticed is that this problem will occur if you try to use a C# style single-line comment to annotate the model declaration in a Razor view:
BAD: #model Int32 // user ID
GOOD: #* user ID *#
#model Int32
Visual Studio syntax highlighting won't flag it as a problem, but it will fail at runtime.

Related

how to find out whether the its view or partial view from controller context?

I want to find out whether i am getting error in View or Partial View. Or in general how do we find out whether the its view or partial view from controller context.
Get the stack trace and try to process from it where the error is. If you need to do this in code you could probably make use of the StackTrace class or the StackTrace from the exception if you are catching one.
you can process the stack trace like this:
var stackTrace = new StackTrace(true);
foreach (var r in stackTrace.GetFrames())
{
Console.WriteLine("Filename: {0} Method: {1} Line: {2} Column: {3} ",
r.GetFileName(),r.GetMethod(), r.GetFileLineNumber(),
r.GetFileColumnNumber() );
}
and the fileName property you could see whether it matches your partial class file.
Best thing you can do is add a bool to ViewBag.isPartial from the controller.
You always want to use holders for such information and never discover them on the view side if you want to be truly in the MVC spirit.
Also, usually it's not a good idea to use the same view both as partial and as a main view. This means that you haven't thought out well the role it plays.
Most common use for such a similar setting would be to change the layout, ie: for mobile, web, etc..

How do I output Massive ORM dynamic query to an MVC 3 View?

When I use Massive ORM to retrieve a record using the .Find() method, it returns a Massive.DynamicModel.Query object which doesn't get along very well with the ASP.MVC 3 View.
Controller:
public ViewResult Details(int id)
{
// Massive ORM Find syntax requires this next statement to use 'dynamic' not 'var'
dynamic table = new Things();
// Thing will return as type Massive.DynamicModel.Query
var Thing = table.Find(ThingId:id);
return View(Issue);
}
In the View, I've tried both #model dynamic and #model Massive.DynamicModel.Query, but neither will allow me to access the properties of my 'Thing' object using the normal #Model.Name syntax.
There is some discussion on here about how to handle ExpandoObjects with MVC3 views, but nothing in particular about the Massive.DynamicModel.Query implementation that has worked for me so far.
Any general ideas how to convert the Massive.DynamicModel.Query object to something typed?
Two words: View models. Strongly typed view models, that's what you should be passing to your views. Not dynamics, not expandos, not anonymous objects, not ViewData, not ViewBag => only strongly typed view models. So start by defining a view model which will represent the data this view will be working with. Then have your controller action do the necessary in order to convert whatever your repositories spit into a view model which will be passed to the view.
Failing to follow this basic rule, your ASP.NET MVC experience could quickly turn into a nightmare.
I think the easiest way is to use ViewBag because it's dynamic already.
You'd better watch the production because it's about Rob's opinionated way of development more than it is about MVC 3, and describes using Massive and other Rob tools.
But even if you don't make sure to check the code sample here for the production (free), to see how he integrates Massive to MVC 3:
https://github.com/tekpub/mvc3
You can see his production controller looks like. Quite interesting ways.
I'm experimenting with dynamics and Massive now. I'm using a dynamic viewModel:
public ActionResult Index() {
_logger.LogInfo("In home");
dynamic viewModel = new ExpandoObject();
var data = _tricksTable.Query("SELECT TOP(10) * FROM Tricks ORDER BY DateCreated DESC");
viewModel.TenTricksNewestFirst = data;
var data2 = _tricksTable.Query("SELECT TOP(10) * FROM Tricks ORDER BY Votes DESC");
viewModel.TenTricksMostPopularFirst = data2;
return View(viewModel);
}
In my view there is no reference to anything strongly typed on the first line eg NOT THIS:
#model IEnumerable<MvcApplication2.Models.Thing>
so in my view I do stuff like this:
#foreach (var item in Model.TenTricksNewestFirst) {
<div class="post block">
<div class="tab-image-block">
<a href="/tricks/#URL.MakeSpacesMinuses(#item.Name)" title="#item.Name">
<img src="/public/images/#item.Thumbnail" alt="#item.Name" class="woo-image thumbnail" /></a>
</div>
<h2 class="title">
#item.Name</h2>
<span class="date">#Dates.ShortDate(#item.DateCreated)</span>
<span class="likes">Likes: #item.Votes</span>
</div>
}
Experience so far is that I'm writing a lot less code.
Because of anonymous type are always annotated as "internal" so you can't access your dynamic type instance from View as they are in different scopes.
I find a better way make it work than using ViewBag. And the answer is Mono.Cecil. Grab it handy from NuGet.
With Mono.Cecil's help you can change MSIL code generated from your ASP.NET MVC project and change the type's accessible modifier to "public".
I write a little console program and host it on GitHub.
You can invoke the program from command line or add a post-build event in your ASP.NET MVC project's Build Events:
"$(SolutionDir)DynamicHelper\bin\Debug\DynamicHelper.exe" "$(TargetPath)"
NOTICE: "DynamicHelper" is the the code's project name and you can change it depending on your situation.

ASP.NET MVC 3 not accepting my German date format settings - why?

I have a new ASP.NET MVC 3 project, and MVC and Razor are all brand new to me... can't figure this one out.
I have a dev machine on US-English Win7 x64, running English versions of VS 2010 Pro SP1 and ASP.NET MVC 3. But the app I'm working on is for a local client, and needs to be all in German and use all the formatting and defaults commonly used here.
In my view model, I have defined a variable of type DateTime and augmented it with some extra hints as to how to display (and edit) it - I need the Swiss-German date formatting, which is: day.month.year (in that order, separated by dots . - not slashes)
public class MyViewModel
{
[Display(Name = "Gültig am")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString="dd.MM.yyyy", ApplyFormatInEditMode=true)]
public DateTime ValidAt { get; set; }
}
(of course, there are more properties in that view model, but those aren't relevant just now)
In my Razor view, I simply use the default stuff set up by the ASP.NET MVC 3 Add View T4 template:
#Html.EditorFor(model => model.ValidAt)
Trouble is: if I enter something like 13.06.2011 (13th of June, 2011) which I believe is valid and conforming to my display and editing formats, I am still getting a client-side validation saying that The value '13.06.2011' is invalid - WHY???
There must be something really fundamental (and probably totally silly) that I'm missing here....
Even though I have set all of this up,
What do you use for client validation? Did you look at Combining validation methods in jQuery Validation plugin with "or" instead of "and" ?

ASP.NET MVC 3 Model Binding - ViewBag.Title clash with input of id="Title"

There seems to be an issue with the ViewBag dynamic properties. Lets say I have:
#{
ViewBag.Title = #Model.CourseName;
}
And then in a form on the page I have:
#Html.TextBox("Title", null, new {style="width:400px;"})
Where Title is the name of a field in a database table.
When the page first opens, text box with an id of "Title" takes the value of the ViewBag.Title dynamic property.
I am a bit hazy on the exact details of Model Binding, but this does seem to be a bug, or if not, if it is something that occurs naturally as a result of the binding process, then it would be nice to be warned of this.
The work around I found, was to rename the ViewBag property to:
#{
ViewBag.Titulo = #Model.CourseName;
}
(Title changed to Titulo - Always good to know another language to avoid name clashes...)
And the issue went away.
However, the question is:
Is this behaviour to be expected? The bug was easy to find (took an hour to figure it out, including writing this question), but I suspect that other bugs might be more, uhmmm, recondite.
EDIT:
Rephrasing the question:
Does the Model Binder automatically bind properties it finds in the ViewBag? Even when an existing property exists in the strongly typed ViewModel I have passed to the page? Surely the ViewModel should take preference?
Html.TextBox checks ViewData/ViewBag values first, then Model. To make sure it takes Model value, you must use Html.TextBoxFor.

mvc 3 issues after converting 2: model + Model + Html + not supported type

I used the conversion tool to convert to mvc 3 from mvc 2.
I create a new partial view, select razor, check "Reference script libraries" (not sure what this means), select "Link (urlme.Model)" for strongly-type, List, OK.
I get the following errors:
List item
The name #model does not exist in the current context
The name Model does not exist in the current context
The name #Html does not exist in the current context
Element 'urlme.Model.Link' is not supported (standard c# class leftover before conversion)
Do I need to add some references?? Any help would be appreciated. I'm stoked to use mvc 3!! Thanks!
I'm guessing you might be missing the Razor sections in Views\Web.config. Please compare the contents of that file with the one generated via the new project template.
Note that Eilon's v2 -> v3 upgrade tool currently only targets MVC3 Beta, so it might not do all the things necessary for RC2. I'm sure Eilon will post an updated version of that tool at some point in the future.

Resources