Razor renderpartial exception - expected '}" - c#

In my code:
#foreach (var post in Model.Posts)
{
Html.RenderPartial("ShowPostPartial", post);
}
i have an excepion on RenderPartial line.
error CS1513: } expected.
What am I doing wrong?

For completeness, here's another way of causing this:
#if(condition)
{
<input type="hidden" value="#value">
}
The problem is that the unclosed element makes it not obvious enough that the content is an html block (but we aren't always doing xhtml, right?).
In this scenario, you can use:
#if(condition)
{
#:<input type="hidden" value="#value">
}
or
#if(condition)
{
<text><input type="hidden" value="#value"></text>
}

This is basically the same answer that Mark Gravell gave, but I think this one is an easy mistake to make if you have a larger view:
Check the html tags to see where they start and end, and notice razor syntax in between, this is wrong:
#using (Html.BeginForm())
{
<div class="divClass">
#Html.DisplayFor(c => c.SomeProperty)
}
</div>
And this is correct:
#using (Html.BeginForm())
{
<div class="divClass">
#Html.DisplayFor(c => c.SomeProperty)
</div>
}
Again, almost same as the earlier post about unclosed input element, but just beware, I've placed div's wrong plenty of times when changing a view.

MY bad.
I've got an error in the partial view.
I've written 'class' instead of '#class' in htmlAttributes.

I've gotten this issue with Razor. I'm not sure if it's a bug in the parser or what, but the way I've solved it is to break up the:
#using(Html.BeginForm()) {
<h1>Example</h1>
#foreach (var post in Model.Posts)
{
Html.RenderPartial("ShowPostPartial", post);
}
}
into:
#{ Html.BeginForm(); }
<h1>Example</h1>
#foreach (var post in Model.Posts)
{
Html.RenderPartial("ShowPostPartial", post);
}
#{ Html.EndForm(); }

The Razor parser of MVC4 is different from MVC3. Razor v3 is having advanced parser features and on the other hand strict parsing compare to MVC3.
--> Avoid using server blocks in views unless there is variable declaration section.
Don’t : \n
#{if(check){body}}
Recommended :
#if(check){body}
--> Avoid using # when you are already in server scope.
Don’t : #if(#variable)
Recommended : #if(variable)
Don't : #{int a = #Model.Property }
Recommended : #{int a = Model.Property }
Refrence : https://code-examples.net/en/q/c3767f

Related

Tag Helper forms: asp-for not working as expected

Thanks for the help so far. I've worked to make sure everything else works so I can focus on this problem. I'm still convinced it'll be an easy fix once we've cracked it. I have the following code, sorry I changed it so much, I had to start again after I made a real mess of the last one without taking a backup.
public IActionResult Index()
{
if(IndexModel.GlobalTasks == null)
{
IndexModel initModel = new IndexModel();
initModel.AllTasks = InitList();
initModel.EmptyTask = new ToDoTask();
IndexModel.GlobalTasks = initModel.AllTasks;
}
IndexModel model = new IndexModel();
model.AllTasks = IndexModel.GlobalTasks;
model.EmptyTask = new ToDoTask("");
return View(model);
}
//Create Task
public IActionResult Create(ToDoTask indexModel)
{
IndexModel.GlobalTasks.Add(indexModel);
return RedirectToAction("Index");
}
And:
#model DE.Models.IndexModel
<h2>To Do List</h2>
<form asp-action="Create">
<input asp-for="EmptyTask" value="#Model.EmptyTask" />
<input asp-for="EmptyTask.TaskDetails" placeholder="New Task" />
<button type="submit">Add Task</button>
</form>
The good news is this creates a new ToDoTask. So the Controller code must be pretty close to spot on. The problem is the View is passing null details to the controller, so I'm getting an empty Task, which isn't what I want.
Any ideas?
Using Tag Helper forms:
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<section >
<input type="text" asp placeholder="Title" asp-for="MyWork.Title"/>
</section >
Your controller action expects a ToDoTask object while your view uses a TaskViewModel object.
Try using the same type in both of them.
In your Create() method you need to instantiate the ToDoTask object, I think. So try this:
[HttpPost]
public IActionResult Create(ToDoTask newTask)
{
newTask = new ToDoTask();
return RedirectToAction("Index");
}
You may also need to return the ToDoTask object.

EditorTemplate inheritance - is there a way

EditorTemplates are great since they allow some kind of "polymorphism" in razor views. But I am missing one "brick" to complete the polymorphism support:
Can an EditorTemplate for a special type inherit from the EditorTemplate for the general type?
Long version:
Given
class SpecialChild : GeneralChild { }
class Parent
{
GeneralChild AGeneralChild { get; set; }
SpecialChild ASpecialChild { get; set; }
}
and two editor templates
#* GeneralChild.cshtml *#
#model GeneralChild
<span>GeneralChild</span>
#* SpecialChild.cshtml *#
#model SpecialChild
<span>SpecialChild is a</span> <span>GeneralChild</span>
What I get (which is why I call it "polymorphism") is:
#* Index.cshtml *#
#Html.EditorFor(m => m.AGeneralChild)
// prints "<span>GeneralChild</span>", however
#Html.EditorFor(m => m.ASpecialChild)
// prints "<span>SpecialChild is a</span> <span>GeneralChild</span>"
That is, even though SpecialChild is a GeneralChild and there is a template for GeneralChild, it auto-selects the SpecialChild.cshtml template. Furthermore, if I remove that template, it falls back to the GeneralChild.cshtml template. In other words, it is possible to reuse a general template or to override it if necessary.
Now for what I would really like:
I would like to reuse the GeneralChild.cshtml template to define the SpecialChild.cshtml template, like a "base method" call in C#. In pseudo-code:
#* SpecialChild.cshtml *#
baseEditorFor()
#section SpecificPart
{
<span>SpecialChild is a </span>
}
#* GeneralChild.cshtml *#
#Html.RenderSection("SpecificPart") <span>GeneralChild</span>
Is something like that supported?
What I have tried so far:
GeneralChild.cshtml:
#model GeneralChild
#{
var extend = ViewData.ContainsKey("Extend")
? (MvcHtmlString)ViewData["Extend"]
: null;
}
#if (extend != null) { #extend }
<span>GeneralChild</span>
SpecificChild.cshtml:
#model SpecialChild
#Html.EditorFor(
m => m, // call editor for my model
"GeneralChild", // but call "base" instead of "this"
new
{
// Hand the HTML to insert as ViewData parameter
Extend = new MvcHtmlString("<span>SpecialChild is a </span>")
})
Unfortunately, #Html.EditorFor(m => m) does not do anything. That makes sense because m => m is not the same expression as the original m => m.ASpecialChild.
I thought I could build up the expression tree by hand, but then I realized that the type arguments within the editor template are (of course) different from the ones in the Index.cshtml. #Html in the original call is typed <Parent> whereas within the template it is <SpecialChild>.
Then I tried another approach which is the closest I got so far:
Within the Index.cshtml I define a razor helper:
#helper SpecialChildEditorFor(Expression<Func<Parent,SpecialChild>> expression)
{
#Html.EditorFor(
expression,
"GeneralChild",
new { Extend = new MvcHtmlString("<span>SpecialChild is a </span>") })
}
Then I call this instead of EditorFor:
#SpecialChildEditorFor(m => m.ASpecialChild)
But of course this lacks the entirety of the the initially mentioned advantages - I can't simply drop this snippet in the EditorTemplates directory, thus "overriding" the GeneralChild.cshtml template. Also, it needs to be explicitly called (so we lost "polymorphism", too). Even more, the razor helper is tied to the Index.cshtml page:
* It has to be defined within the page where it is used.
* It relies on expression to have the same type arguments as the one the page needs.
Use Partial in editor template insted of #Html.EditorFor(m => m, ...):
#model SpecialChild
#{
ViewData["Extend"] = new MvcHtmlString("<span>SpecialChild is a </span>");
}
#Html.Partial("~/Views/Shared/EditorTemplates/GeneralChild.cshtml", Model)

Razor code comments

I'm trying to re-write very long complex if statements and switch statements inside my razor view . So comments would definetly help the readibility. Problem is this
#if(IsManager(){
switch(Model.ReportType){
case ReportType.NewReport:
if (case1){
// bla bla bla
//
}
else if (case2){
// bla blab bla
//
}
break;
case ReportType.FooReport:
if (fooBar){
....
so any ways, there is very simplified example of something that would be in a razor code block. Now if I want to add simple comments in there to help readibility - it all breaks!! ex.
#if(IsManager(){ #* TALENT MANAGER *#
switch(Model.ReportType){
case ReportType.NewReport:
that makes intellisense get really mad for some reason, I tried this style of comment
#if(IsManager(){ // TALENT MANAGER
switch(Model.ReportType){
case ReportType.NewReport:
no luck , am I doing something wrong??
You can group reusable (or complex) view code into a helper. Helpers are definable in their own file or in a view.
#helper DoSomethingWhenManager(bool isManager, ReportModel model)
{
if(isManager)
{
switch(model.ReportType) // This is a comment about the report
{
// ...
}
{
}
View:
<div>
#DoSomethingWhenManager(IsManager(), Model)
</div>
This one works fine for me
#if (1 < 9) { //Hello
<b>Hey, there!</b>
}
I use Visual Studio 2013 Express for Web

asp.net mvc 3 silverlight like validation

MAIN QUESTION
As the title says, i'm asking if anyone knows how to create a validation structure similar to silverlight's dataform. Any hints, materials , ideas would be welcome. I'd like to do a validation like this:
(You can check this out here)
DETAILS
I've been trying to something like the example above, but without results until now. Mostly because i dont' know how the validation message helper works. I've managed to a single validation message by taking the data-val-number attribute and set it into a link title (using a third party jquery plugin callled qTip to show a tooltip error message). However, i can't do the same thing if there are more than one validation.
So, is it possible to rewrite the validation message helper? I'd like to understand more how it shows the validation messages so i can put them on any html content. This would do the tooltip part and i could set as many messages as i want, with any formatting i desire.
And i'd like to be able to show the validation messages through any jquery events (mouseover, click, dblclick, ready, etc.). As far as i understand on it's actual implementation, the validation only occurs when the user changes focus from the actual input to another html element.
I highly recommend that you checkout the validation rules section in Professional ASP.NET MVC. It shows how to do exactly what you describe with ASP.NET MVC v1 and it works all the way up through v3.
The displayed user interface is slightly different; however, you can check the output and write your own CSS to make it look just like your screenshot.
For a quick example:
Action Result
try
{
// code
}
catch
{
foreach (var issue in std.GetRuleViolations())
{
ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
}
Model
public IEnumerable<RuleViolation> GetRuleViolations()
{
if (!String.IsNullOrEmpty(this.Phone) && !Utility.IsValidPhoneNumber(this.Phone))
{
yield return new RuleViolation("Phone is invalid. Try this format: ###-###-####.", "HomePhone");
}
yield break;
}
Edit View
<%
using (Html.BeginForm())
{
%>
<fieldset>
<legend>Edit</legend>
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<%= Html.TextBox("Phone", Model.Phone)%>
<%= Html.ValidationMessage("Phone", "*")%>
<!-- more fields go here -->
</fieldset>
<% } %>
rule violation class -- lifted from link
public class RuleViolation
{
public string ErrorMessage { get; private set; }
public string PropertyName { get; private set; }
public RuleViolation(string errorMessage)
{
ErrorMessage = errorMessage;
}
public RuleViolation(string errorMessage, string propertyName)
{
ErrorMessage = errorMessage;
PropertyName = propertyName;
}
}

Nested operations with Razor View Engine

I cannot figure out how to do "nested" operation in Razor. For example how to use IF inside FOREACH. VisualStudio throws compile-time error on following block, saying "Invalid expression term 'if' "
#foreach (var document in Model) {
#if (document.Item.Count > 0) {
<div>
#MvcHtmlString.Create(document.Items[0].ContentPresenter)
</div>
}
}
Don't you just need to drop the # off the #if and make it:
#foreach (var document in Model) {
if (document.Item.Count > 0) {
<div>
#MvcHtmlString.Create(document.Items[0].ContentPresenter)
</div>
}
}
Sorry I haven't worked with Razor but isn't its selling point the automatic switching back and forth between code and HTML based on context?

Categories